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) {
    // Your logic here
    char digits[5];
    int index=0;

    if(num == 0)
    {
        putchar('0');
        return;
    }

    while(num)
    {
        if((num&0x0F) < 10)
        {
            digits[index++] = (num&0x0F) + '0';
        }
        else
        {
            digits[index++] = (num&0x0F) + 'A' - 10;
        }
        num = (num>>4);
    }
        // Print in reverse (MSB first)
    for (int j = index - 1; j >= 0; j--) {
        printf("%c",digits[j]);
    }
}

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

Solving Approach

 

 

 

Loading...

Input

255

Expected Output

FF