Convert Integer to Hex String Without sprintf or itoa functions

Code

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

void print_hex(uint16_t num) {
    // Process 4 nibbles (16 bits = 4 hex digits)
    if (num==0) {printf("%d",num); return;}
    for (int i = 12; i >= 0; i -= 4) {        // Start from MSB nibble
        uint16_t nibble = (num >> i) & 0xF;    // Extract current nibble
        if (nibble == 0) continue;
        if (nibble < 10) {
            printf("%c", '0' + nibble);
        } else {
            printf("%c", 'A' + (nibble - 10));
        }
    }
    printf("\n");  // Optional: for clean output
}

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

Solving Approach

 

 

 

Upvote
Downvote
Loading...

Input

255

Expected Output

FF