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

Code

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

void print_binary(uint16_t val) {
    int loop_end = 0; 
    val >= 256 ? loop_end = 16 : loop_end = 8;

    char res[loop_end + 1] = "";
    res[loop_end] = '\0';

    for (int i = 0; i < loop_end; i++)
    {
        if (((val >> ((loop_end - 1) - i)) & 1) == 1)
        {
            res[i] = '1'; 
        }
        else
        {
            res[i] = '0';
        }
    }

    printf("%s",res);

/*
Input: val = 10  = 0b1010
Output: 0000 1010

build output: {1}

*/
}

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

Solving Approach

 

 

 

Upvote
Downvote
Loading...

Input

10

Expected Output

00001010