Convert Integer to Hex String Without sprintf or itoa functions

Code

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

void print_hex(uint16_t num) {
int len = 4;
char buff[len];

if(!num)putchar('0');

    while(num){
        
        uint16_t y = (num & 0x0f);

        if(y > 9) buff[len] = (y + 'A'-10);
    
        else buff[len] = y + '0';
        
        num >>= 4;
        len--;
    }
    for(int i=1;i<=4;i++){
        if(buff[i])putchar(buff[i]);
    }
}

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

Solving Approach

 

 

 

Upvote
Downvote
Loading...

Input

255

Expected Output

FF