Convert Integer to Hex String Without sprintf or itoa functions

Code

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

void print_hex(uint16_t num)
{
    char str[20];
    int i=0,rem;
    if (num==0) {
        printf("%c",num+'0');
        return;
    }
    while(num>0){
        rem=(num%16);
        if (rem>=10) str[i]=(rem-10)+'A';
        else str[i]=rem+'0';
        i++;
        num/=16;
    }
   
    for (int j=i-1;j>=0;j--){
        printf("%c",str[j]);
    }
}

int main()
{
    uint16_t num;
    scanf("%hu", &num);

    print_hex(num);
    return 0;
}

Solving Approach

 

 

 

Upvote
Downvote
Loading...

Input

255

Expected Output

FF