Convert Integer to Hex String Without sprintf or itoa functions

Code

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

void print_hex(uint16_t num) {
    // Your logic here
    if (num == 0) {
        printf("0");
        return;
    }

    char buffer[10];
    int i = 0;
    while(num) {
        uint8_t remain = num % 16;
        buffer[i++] = ( ( remain < 10 ) ? ( '0' + remain ) : ( 'A' + remain  - 10 ) );
        num /= 16;
    }

    for(int j = i - 1; j >= 0; --j) {
        printf("%c", 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