Convert Integer to Hex String Without sprintf or itoa functions

Code

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

void print_hex(uint16_t num) {
    if (num == 0){
        printf("0"); 
        return; 
    }
    char digits[17] = "0123456789ABCDEF";
    char buf[24]; 
    int i = 0; 
    while (num != 0){ 
        int hex = num % 16; 
        buf[i] = digits[hex]; 
        num /= 16; 
        i++; 
    }

    for (int j = i - 1; j >= 0; j--){ 
        printf("%c", buf[j]); 
    }
    // Your logic here
}

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

Solving Approach

 

 

 

Upvote
Downvote
Loading...

Input

255

Expected Output

FF