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

Back To All Submissions
Previous Submission
Next Submission

Code

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

void print_binary(uint16_t val) {
    uint8_t bit = 0;
    bit = val<= 255 ? 8:16;

    char bits[16];
    int i = 0;
    while(val) {
        bits[i++] = val % 2 +'0';
       val = val/2; 
    }
    for(int k= bit-1; k >= i; k--) {
        printf("0");
    }
    for(int k = i -1; k>=0; k--) {
        printf("%c", bits[k]);
    }
}

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

Solving Approach

 

 

 

Was this helpful?
Upvote
Downvote