116. Convert Decimal Number to Binary or Hex Without itoa function

Back To All Submissions
Previous Submission
Next Submission

Code

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

void print_base(uint16_t num, uint8_t base) {
    const char offset_dec = '0';
    const char offset_hex = 'A' - 10;
    char str[17];

    // first decode the number
    if (base == 2) {
        // decode binary number
        for (int i = 15; i >= 0; i--) {
            str[15 - i] = ((num >> i) & 1) + offset_dec;
        }
        str[16] = '\0';
    } else if (base == 16) {
        // decode hexadecimal number
        for (int i = 3; i >= 0; i--) {
            char digit = (num >> (i * 4) & 0xF);
            str[3 - i] = digit + ((digit < 10) ? offset_dec : offset_hex);
        }
        str[4] = '\0';
    }

    // then remove leading zeros
    char *pstr = str;
    while (*pstr == '0') {
        pstr++;
    }

    // now we can print the string
    printf("%s", (*pstr) ? pstr : "0");
}

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

    print_base(num, base);
    return 0;
}

Solving Approach

 

 

 

Was this helpful?
Upvote
Downvote