Convert Integer to Hex String Without sprintf or itoa functions

Code

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

void print_hex(uint16_t num) {
    char table[] = "0123456789ABCDEF";
    int start = 0;
    for (int i = 12; i >= 0; i -= 4){
        uint16_t digit = (num >> i) & 0xF;
        if (digit != 0 || start || i == 0){
            putchar(table[digit]);
            start = 1;
        }
    }
    // 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