Convert Decimal Number to Binary or Hex Without itoa function

Code

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

int starting_point=15;

void print_base(uint16_t num, uint8_t base) {
    // Your logic here
    switch(base) {
        case 2:
            // get FSB
            for(int i=0;i<16;i++) {
                if(num>>(15-i)&1) {
                    starting_point=i;
                    break;
                }
            }

            // print binary
            for(int i=starting_point;i<16;i++) {
                    printf("%d", (num>>(15-i))&1);
            }
        break;
        case 16:
            // print in hex
            printf("%02X", num);
        break;
    }
}

int main() {
    uint16_t num;
    uint8_t base;
    scanf("%hu %hhu", &num, &base);

    print_base(num, base);
    return 0;
}

Solving Approach

 

 

 

Upvote
Downvote
Loading...

Input

10 2

Expected Output

1010