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 str[20];
    int first_zero_found = 0, index = 0, number = 0;
    if(num==0)
    {
        printf("%hu", num);
        return;
    }
    
    for(uint8_t i=0; i<4; i++)
    {
        if(!first_zero_found)
        {
            if(!(((num >> (12-4*i)) & 15)))
                continue;
            else
            {
                first_zero_found = 1;
                number = ((num >> (12-4*i)) & 15);
                str[index++] = (number < 10) ? (number + '0'): (number + 'A' - 10);
            }
        }
        else
        {
            number = ((num >> (12-4*i)) & 15);
            str[index++] = (number < 10) ? (number + '0'): (number + 'A' - 10);
        }
    }
    if(index==0)
        str[index++] = '0';
    str[index] = '\0'; 
    printf("%s", str);
}

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

Solving Approach

 

 

 

Upvote
Downvote
Loading...

Input

255

Expected Output

FF