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
    uint8_t map[17] = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
    if(num==0){
        putchar('0');
        return;
    }

    uint8_t buffer[5];
    uint8_t i = 0;

    while(num){
        buffer[i++] = map[num%16]; 
        num /= 16;
    }

    for(int j=i-1;j>=0;j--){
        putchar(buffer[j]);
    }
}

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

Solving Approach

 

 

 

Upvote
Downvote
Loading...

Input

255

Expected Output

FF