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
    int n;
    


    if(val <= 255){
        uint8_t ex;
            uint8_t shift;
        n=8;
        shift = 0x80;
       while(n!=0){
        ex = shift & val;
        //printf(" shift : %d\n",ex);
        if(ex >0) printf("1");
        else printf("0");
        shift = shift >> 1;
        n--;

       }
    }
    else {
        uint16_t ex;
            uint16_t shift;
        n=16;
        shift = 0x8000;
         //printf(" shift : %d\n",shift);
       while(n!=0){
       

         ex = shift & val;
         //printf(" shift : %d\n",shift);

        if(ex > 0) printf("1");
        else printf("0");
        shift = shift >> 1;
        n--;

       }
    }
  
}

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

Solving Approach

 

 

 

Upvote
Downvote
Loading...

Input

10

Expected Output

00001010