Convert Decimal Number to Binary or Hex Without itoa function

Code

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

void print_base(uint16_t num, uint8_t base) {
    bool found_first_set_bit = false;
    // Your logic here
    if (base == 2){
        for (int i=7; i>=0; i--){
            if ((num>>i)&1) {
                found_first_set_bit = true;
            }
            if (found_first_set_bit) {
                printf("%hhu",(num>>i)&1);
            }
        }
        if (!found_first_set_bit) printf("0");
    }
    else {
        for (int i=12; i>=0; i=i-4){
            uint8_t val = (num>>i)&0xF;
            if (val){
                found_first_set_bit = true;
            }
            if (found_first_set_bit) {
                if (val < 10) printf("%d",val);
                else printf("%c",val-10+'A');
            }
        }
        if (!found_first_set_bit) printf("0");
    }
}

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