Convert Integer to Hex String Without sprintf or itoa functions

Code

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

void print_hex(uint16_t num) {
    char hex[] = "0123456789ABCDEF";
    if(num == 0) printf("0");
    else {
        char* s = (char *)malloc(10 * sizeof(char));
        int i=0;
        while(num) {
            s[i++] = hex[num % 16];
            num = num/16;
        }
        i--;
        
        while(i>=0){
            printf("%c",s[i]);
            i--;
        }

    }
}

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

Solving Approach

 

 

 

Upvote
Downvote
Loading...

Input

255

Expected Output

FF