101. Convert Integer to Hex String Without sprintf or itoa functions

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

// Convert number to hex string manually and print it
void print_hex(uint16_t num) {
    if (num == 0) {
        printf("0");
        return;
    }

    char hex_digits[] = "0123456789ABCDEF";
    char buffer[5];  // max 4 hex digits + '\0'
    int i = 0;

    while (num > 0) {
        buffer[i++] = hex_digits[num % 16];
        num /= 16;
    }

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

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

Why It Matters in Firmware?

  • Useful for hex dumps, register visualization, debug messages
  • Lightweight and works without libc
  • Avoids runtime cost of sprintf() and its buffer overhead

Logic Summary

  • Use % 16 to get each hex digit
  • Convert digit to ASCII using hex_digits[]
  • Store digits in reverse, then print them in correct order

     
Loading...

Input

255

Expected Output

FF