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) {
   int bit;
   int mask;

   if(val <= 255) {
    bit = 8;
    mask = 0x80;
   } else {
    bit = 16;
    mask = 0x8000;
   }

   for(int i=0; i<bit; i++){
    if((mask & val)) printf("1");
    else{
    printf("0");
   }
   mask >>=1;
   }
    printf("\n");
}

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

Solving Approach

 

 

 

Was this helpful?
Upvote
Downvote