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 temp[16];
    int cnt=0;
    if (val<=255){
        while (cnt<8){
            temp[cnt++]=val%2;
            val/=2;
        }
        
    }

    else if (val>255){
        while (cnt<16){
            temp[cnt++]=val%2;
            
            val/=2;
        }
    }
    for (int i=0;i<cnt;i++){
          printf("%c",temp[cnt-1-i]+'0');
    }
}

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

Solving Approach

 

 

 

Upvote
Downvote
Loading...

Input

10

Expected Output

00001010