Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

c format input to binary and then output

I want to take an user input with the following code:

uint32_t value;
printf("value: ");
scanf("%"SCNu32, &value);

My question now is, how would I use the user input (in my case value) and then return it formatted as a binary number without loops in the function print_binary? The output must be 32bits after the 0b. I can’t use any kind of loops anywhere.

#include <inttypes.h>
#include <stdio.h>
#include <stdlib.h>

void print_binary(uint32_t value){

    printf("%d = 0b",value);
    //I want to print the variable value with a fixed length of 32 and that it is 
    //binary with the starting index of 0bBinaryValueOfNumber.
    return;
}

int main(void) {
    uint32_t value;
    printf("value: ");
    if (scanf("%"SCNu32, &value) != 1) {
        fprintf(stderr, "ERROR: While reading the 'uint32_t' value an error occurred!");
        return EXIT_FAILURE;
    }
    printf("\n");
    print_binary(value);
    printf("\n");
    return EXIT_SUCCESS;
}

I do also have the following examples:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

If the user input is 5, the function should return "5 = 0b00000000000000000000000000000101".

>Solution :

If you cannot use loops, you could use recursion:

void print_bin(uint32_t n, int digits) {
    if (digits > 1) print_bin(n >> 1, digits - 1);
    putchar('0' + (n & 1));
}

void print_binary(uint32_t value) {
    printf("%d = 0b", value);
    print_bin(value, 32);
    printf("\n");
}

Alternative approach using tail recursion:

void print_bin(uint32_t n, int digits) {
    putchar('0' + ((n >>-- digits) & 1));
    if (digits > 0) print_bin(n, digits);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading