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 i = 0;
    char res[20];

    if(num == 0){
        printf("0"); return;
    }

    while(num > 0){
        int tmp = num % 16;
        if(tmp < 10){
            res[i] = tmp + '0';
            i++;
        }

        else{
            res[i] = tmp - 10 + 'A';
            i++;
        }
        num /= 16;
    }
    for(int j = i - 1; j >= 0; j--){
        printf("%c", res[j]);
    }
}

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

Solving Approach

 

 

 

Upvote
Downvote
Loading...

Input

255

Expected Output

FF