All submissions

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

Code

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

#if 0
#define BYTE_2_BIN_FMT "%c%c%c%c%c%c%c%c"
#define BYTE_2_BIN(byte) \
    ((byte & 0x80)? '1': '0'), \
    ((byte & 0x40)? '1': '0'), \
    ((byte & 0x20)? '1': '0'), \
    ((byte & 0x10)? '1': '0'), \
    ((byte & 0x08)? '1': '0'), \
    ((byte & 0x04)? '1': '0'), \
    ((byte & 0x02)? '1': '0'), \
    ((byte & 0x01)? '1': '0')


void print_binary(uint16_t val) {
    if (val & 0xFF00) {
        printf(BYTE_2_BIN_FMT, BYTE_2_BIN((val >> 8)));
    }
    printf(BYTE_2_BIN_FMT, BYTE_2_BIN((val & 0xFF)));
    printf("\n");
}
#else
void print_binary(uint16_t val) {
    int bits = 8;
    if (val & 0xFF00)
        bits = 16;

    for (int i = bits - 1; i >= 0; i--) {
        putchar(((val >> i) & 1) + '0');
    }
    putchar('\n');
}
#endif

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

Solving Approach

 

 

 

Loading...

Input

10

Expected Output

00001010