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) {
    // Process each nibble
    int i;
    if(num == 0){
        printf("0");
        return;
    }
    for(i = 0; i < 4; i++){
        uint16_t mask = (0xf << (12 - 4*i));
        uint8_t nibble = (num & mask) >> (12 - 4*i);
        if(nibble){
            if(nibble < 10){
                printf("%c", '0' + nibble);
            }else{
                printf("%c", 'A' + nibble - 10);
            }
        }
    }
}

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

Solving Approach

 

 

 

Loading...

Input

255

Expected Output

FF