All submissions

Convert Decimal Number to Binary or Hex Without itoa function

Code

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

char dtoh(uint8_t dec) {
#if 0
    switch (dec) {
        case 0:
        case 1:
        case 2:
        case 3:
        case 4:
        case 5:
        case 6:
        case 7:
        case 8:
        case 9:
            return dec + '0';
        case 10:
        case 11:
        case 12:
        case 13:
        case 14:
        case 15:
            return (dec - 10 + 'A');
        default:
            // should not happen
            return 'X';
    }
#endif
    // alternate
    if (dec < 10)
        return dec + '0';
    else if (dec < 16)
        return (dec - 10 + 'A');
    else
        return 'X';
}

void print_base(uint16_t num, uint8_t base) {
    // state variable to prevent printing of leading zeros
    int printing = 0;

    if (base == 2) {
        for (int i = 15; i >= 0; i--) {
            if (!printing) {
                if ((num >> i) & 1)
                    printing = 1;
            }

            if (printing)
                putchar(((num >> i) & 1) + '0');
        }
    } else if (base == 16) {
        for (int i = 12; i >= 0; i -= 4) {
            char nibble = (num >> i) & 0xF;
            if (!printing)
                if (nibble)
                    printing = 1;
            if (printing)
                putchar(dtoh(nibble));
        }
    } else {
        printf("Unsupported base %0d\n", base);
        return;
    }

    // if not printing after handling all positions, val == 0;
    if (!printing)
        putchar('0');

    putchar('\n');
}

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

    print_base(num, base);
    return 0;
}

Solving Approach

 

 

 

Loading...

Input

10 2

Expected Output

1010