Convert Integer to Hex String Without sprintf or itoa functions

Code

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

void print_hex(uint16_t num) {
    // Your logic here
    char res_buf[10];
    int i =0;
    if(num == 0)
    {
        res_buf[i++] = '0';
    }
    while(num !=0)
    {
        uint8_t temp = num%16;
        if(temp<=9)
        {
            res_buf[i++] = temp+'0';
        }
        else
        {
            res_buf[i++] = temp-10 + 'A';
        }
        num = num/16;
    }
    // res_buf[i] = '\0';
    for(int j=i-1; j>=0; j--)
    {
        printf("%c", res_buf[j]);
    }
}

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

Solving Approach

 

 

 

Upvote
Downvote
Loading...

Input

255

Expected Output

FF