All submissions

Convert Integer to Hex String Without sprintf or itoa functions

Code

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

void print_hex(uint16_t num) {
    char buffer[20];
    int i = 0;

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

    uint8_t hexbit;
    while (num > 0) {
        hexbit = num & 0xF;
        if ((hexbit >= 0) && (hexbit <= 9)) buffer[i++] = hexbit + '0';
        else if ((hexbit >= 10) && (hexbit <= 15)) buffer[i++] = (hexbit-10)+'A';
        num = num >> 4;
    }

    for (int j=i-1; j>=0; j--) {
        putchar(buffer[j]);
    }
}

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

Solving Approach

 

 

 

Loading...

Input

255

Expected Output

FF