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
int count =0;
    char str[100];
     if(num==0) printf("0");

    while (num > 0) {
        uint8_t remainder = num % 16;

        if (remainder < 10)
            str[count++] = remainder + '0';
        else
            str[count++] = (remainder - 10) + 'A';

        num = num / 16;
    }
    
    for(int i=count-1;i>=0;i--){
        printf("%c" ,str[i]);

    
}
}

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

Solving Approach

 

 

 

Upvote
Downvote
Loading...

Input

255

Expected Output

FF