Convert Integer to Hex String Without sprintf or itoa functions

Code

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

void print_hex(uint16_t num) {
    char buffer[5]; // Max 4 hex digits + null terminator
    int i = 0;

    if (num == 0) {
        printf("0\n");
        return;
    }

    while (num > 0) {
        uint8_t digit = num % 16;
        buffer[i++] = (digit < 10) ? ('0' + digit) : ('A' + digit - 10);
        num /= 16;
    }

    // Print in reverse order
    for (int j = i - 1; j >= 0; j--) {
        putchar(buffer[j]);
    }
    putchar('\n');
}

int main() {
    uint16_t num;
    scanf("%hu", &num);
    print_hex(num);
    return 0;
}

Solving Approach

1. Handle Zero Case

  • If num == 0, print '0' and return — this is a special case.

2. Initialize a Buffer

  • Use a character array buffer[5] to store up to 4 hex digits (plus null terminator if needed).
  • Use an index i = 0 to track how many digits you’ve stored.

3. Extract Hex Digits

  • Loop while num > 0:
  • digit = num % 16 → gives the last hex digit
  • Convert digit to character:
    • If digit < 10: '0' + digit
    • Else: 'A' + digit - 10 (for values 10–15)
  • Store the character in buffer[i++]
  • num = num / 16 → move to the next digit

4. Print in Reverse

  • Hex digits were stored from least significant to most significant.
  • Loop from i - 1 down to 0 and print each character using putchar()

 

 

Upvote
Downvote
Loading...

Input

255

Expected Output

FF