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) {
    //1. Calculate number of bits required to represent value
    int bits = (val <=255) ? 8 : 16;
    
    //2. Move a '1' mask from end to start & with 1 and print 1's and 0's accordingly
    for(int i=0;i<bits;i++){
        ((1 << bits-i-1) & val) ? printf("1") : printf("0");
    }
}

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

Solving Approach

 

 

 

Was this helpful?
Upvote
Downvote