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 hex_string[4] = {0};
    uint8_t index = 0;
    uint8_t non_zero_nibble_encountered = 0;

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

    for (int i = 0; i < 4; i++) {
        uint8_t nibble = (num >> i*4) & 0xF; 
        if (nibble <= 9) {
            hex_string[index++] = nibble + 48;
        } else if (nibble > 9) {
            hex_string[index++] = nibble + 55;
        }
    }

    for (int i = index-1; i >= 0; i--) {

        if (hex_string[i] != '0') {
            non_zero_nibble_encountered = 1;
        }

        if (non_zero_nibble_encountered) {
            printf("%c", hex_string[i]);
        }
    }
}

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

Solving Approach

 

 

 

Upvote
Downvote
Loading...

Input

255

Expected Output

FF