Convert Integer to Hex String Without sprintf or itoa functions

Code

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

void print_hex(uint16_t num) {
    char hexDigits[]="0123456789ABCDEF";
    char hexString[5];
    int index = 0;

    // Check if the number is 0 first, since 0 is a special case
    if (num == 0) {
        printf("0\n");
        return;
    }

    for (int i = 12; i >= 0; i -= 4) {
        int digit = (num >> i) & 0xF;  // Extract a nibble (4 bits)
        if (digit != 0 || index > 0) {
            hexString[index++] = hexDigits[digit];
        }
    }
    hexString[4] = '\0'; // Null terminator
    printf("%s\n", hexString); // Print the resulting hex string
}

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

Solving Approach

 

 

 

Upvote
Downvote
Loading...

Input

255

Expected Output

FF