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
    int cnt = 16;
    while((cnt > 0) && (((num>>(cnt-1)) & 1) == 0 ) )
        cnt--;

    int hex = cnt/4 + (cnt%4);

    if(hex == 0)
    {
        printf("0");
        return;
    }

    //printf("%d ",hex);

    for(int n = 0; n < hex ; n++)
    {
        char ch = num>>(4*(hex-n-1)) & 0xF;

        printf("%c",(ch < 10 )? ch+48 : ch+55  );
    }

}

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

Solving Approach

 

 

 

Loading...

Input

255

Expected Output

FF