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){
        putchar('0');
        return;
    }
    for(int i = 3; i >= 0; i--){
        uint8_t nibble = ((num >> (i * 4)) & 0x0F);
        if(nibble){
            putchar(nibble > 10 ? 'A' + nibble - 10 : '0' + nibble);
        }
    }
}

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

Solving Approach

 

 

 

Upvote
Downvote
Loading...

Input

255

Expected Output

FF