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 hexstr[5];
    int8_t i = 0;
    uint8_t value = 0;
    hexstr[4] = '\0';
    do{
        value = num % 16;
        hexstr[3-i] = (value < 10) ? ('0' + value) : ('A' +  (value - 10));
        num/= 16;
        i++;
    }while(num);
    printf("%s",&hexstr[3-i+1]);
}

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

Solving Approach

 

Keep dividing by 16 until 0. Put all remainders in a char array after converting into hex digits. terminate with null character to make it a string 

 

Upvote
Downvote
Loading...

Input

255

Expected Output

FF