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) {
    char hexa[100];
    uint16_t tmp;
    int i, j;

    switch (base) {

        case 2: {
            int started = 0;

            if (num == 0) {
                printf("0");
                break;
            }

            for (i = 15; i >= 0; i--) {
                tmp = (num >> i) & 1;
                if (tmp || started) {
                    started = 1;
                    printf("%d", tmp);
                }
            }
            break;
        }

        case 16: {
            if (num == 0) {
                printf("0");
                break;
            }

            i = 0;
            while (num != 0) {
                tmp = num % 16;
                hexa[i++] = (tmp < 10) ? (tmp + '0') : (tmp + 'A' - 10);
                num /= 16;
            }

            for (j = i - 1; j >= 0; j--)
                printf("%c", hexa[j]);

            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