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
    uint8_t bits = (val <= 255) ? 8:16;
    for(int8_t i = bits - 1; i>=0; i--)//if the loop uses uint8_t i, and when i reaches 0, it wraps around to 255 instead of stopping. This causes an infinite loop or buffer overflow, especially when printing 8-bit values
    {
        printf("%u",((val>>i)&1));//putchar((val & (1 << i)) ? '1' : '0');
    }
}

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

Solving Approach

  • Decide bit-width (8 or 16)
  • Loop from MSB to LSB
  • Use bitmask and shift to print '1' or '0'

 

 

Upvote
Downvote
Loading...

Input

10

Expected Output

00001010