Convert Integer to Hex String Without sprintf or itoa functions

Code

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

static const char hex[] = "0123456789ABCDEF";

void print_hex(uint16_t num) {
    // Your logic here

    uint8_t start = 0;
    int8_t idx = 16;

    while(idx > 0) {
        idx -= 4;
        uint8_t chop_val = ((num >> idx) & 0xF);

        if (chop_val > 0 && !start) {
            start = 1;
        }
        if (start || idx == 0) {
            printf("%c", hex[chop_val]);
        }
    }

}

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

Solving Approach

 

 

 

Upvote
Downvote
Loading...

Input

255

Expected Output

FF