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) {
    // Your logic here
    char buffer[17]; // enough for 16-bit binary + null
    int i = 0;

    // Special case: num = 0
    if (num == 0) {
        printf("0\n");
        return;
    }
     while (num > 0) {
        uint8_t rem = num % base;

        if (rem < 10)
            buffer[i++] = '0' + rem;
        else
            buffer[i++] = 'A' + (rem - 10); // for hex (A-F)

        num /= base;
    }

    // Reverse and print
    for (int j = i - 1; j >= 0; j--) {
        printf("%c", buffer[j]);
    }

    printf("\n");
}

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