1

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".

2
  • thanks for the quick solution, unfortunately I'm not allowed to use for loops or while loops. Is there another possibility? Commented Nov 20, 2021 at 16:40
  • sry did the edit right now, my bad. Commented Nov 20, 2021 at 16:44

1 Answer 1

2

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);
}
Sign up to request clarification or add additional context in comments.

3 Comments

Interesting >>-- "operator".
@chux-ReinstateMonica: A dangerous one: a poisonous dart fired from a blowgun. Illegal in many places but not in France
Now I thinking, what the longest "operator" in C? n -->>-- digits is 6. Hmmm.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.