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) {
    // Your logic here
    char buffer[33]; // Large enough for a 32-bit binary string + null terminator
    char digits[] = "0123456789ABCDEF";
    int i = 0;

    // Handle zero explicitly
    if (num == 0) {
        printf("0\n");
        return;
    }

    // Step 1: Extract digits in reverse order
    while (num > 0) {
        buffer[i++] = digits[num % base]; // Get remainder
        num /= base;                      // Integer division
    }
    buffer[i] = '\0'; // Null-terminate the string

    // Step 2: Reverse the buffer to get the correct order
    for (int j = 0; j < i / 2; j++) {
        char temp = buffer[j];
        buffer[j] = buffer[i - j - 1];
        buffer[i - j - 1] = temp;
    }

    printf("%s\n", buffer);
}

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