Home > Software engineering >  c format input to binary and then output
c format input to binary and then output

Time:11-21

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:

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

CodePudding user response:

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);
}
  • Related