Convert Integer to Hex String Without sprintf or itoa functions

Code

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

void print_hex(uint16_t num) {
    // Your logic here
    char buf[10];
    int i = 0;
    if (num == 0) {
        printf("0");
    } else {
        while (num != 0) {
            int tmp = (num % 16) + '0';
            if ('0' <= tmp && '9' >= tmp) {
                buf[i++] = ((num % 16) + '0');
            } else {
                buf[i++] = ((num % 16) - 10 + 'A');
            }
            
            num /= 16;
        }

        i--;
        while (i >= 0) {
            printf("%c", buf[i]);
            i--;
        }
    }
}

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

Solving Approach

The solution is more clear than my logic

hex_digits array is a kick

 

 

Upvote
Downvote
Loading...

Input

255

Expected Output

FF