Print Binary Representation of an 8-bit or 16-bit Value

Code

#include <stdio.h>
#include <stdint.h>

void print_binary(uint16_t val) {
    // Your logic here
    char c ;
    int i = (val <= 255) ? 7 : 15;
    for(; i >= 0; --i)
    {
        c = ((val >> i) & 1) + '0';
        putchar(c);
    }
    putchar('\n');
}

int main() {
    uint16_t val;
    scanf("%hu", &val);
    print_binary(val);
    return 0;
}

Solving Approach

Get the i-th bit of the integer and print it within a loop from MSB to LSB.

 

 

Upvote
Downvote
Loading...

Input

10

Expected Output

00001010