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 result[20];
    int val = num < 0 ? 0 - num : num; 
    int i = 0; 
    while (val > 0)
    {
        int index_s =  (val % 16);
        if (index_s > 10)
         {
            result[i++] = (index_s - 10)  + 'A' ;
            //printf("%c" , (index_s)  + 'A' );
         }
         else 
         {
             result[i++] = index_s + '0';
         }
       
        val = val /16;

    }
    if ( num < 0)
    {
        printf("- ");
    }
    if (num == 0)
    {
        printf("%d",num);
    }
    for (int c = i - 1 ; c >= 0   ; c-- )
    {
        printf("%c",result[c]);
    }
}

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

Solving Approach

 

 

 

Upvote
Downvote
Loading...

Input

255

Expected Output

FF