Convert Decimal Number to Binary or Hex Without itoa function

Code

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

char findHex(uint8_t num)
{
    char c;
    if(num<=9)
    {
        c = 48 + num;
    }
    else
    {
        c = 65 + (num-10);
    }
    return c;
}

void print_base(uint16_t num, uint8_t base) {
    // Your logic here
    if(base == 2)
    {
        char binary[16];
        for(uint8_t x=0;x<16;x++)
        {
            binary[x] = (0x1 & (num>>(15-x))) ? '1':'0';
        }
        uint8_t first_one = 0;
        for(uint8_t x=0;x<16;x++)
        {
            if(binary[x]== '1' && first_one==0)    first_one = 1;
            if(first_one == 1)  printf("%c", binary[x]);
        }
    }
    else
    {
        char hex[4];
        hex[0] = findHex(num>>12 & 0xf);
        hex[1] = findHex(num>>8 & 0xf);
        hex[2] = findHex(num>>4 & 0xf);
        hex[3] = findHex(num & 0xf);
        
        uint8_t first_nonzero = 0;
        for(uint8_t x=0;x<4;x++)
        {
            if(hex[x]!='0' && first_nonzero==0)    first_nonzero = 1;
            if(first_nonzero == 1)  printf("%c", hex[x]);
        }
    }
}

int main() {
    uint16_t num;
    uint8_t base;
    scanf("%hu %hhu", &num, &base);
    if(num==0)  
    {
        printf("0");
        return 0;
    }

    print_base(num, base);
    return 0;
}

Solving Approach

 

 

 

Upvote
Downvote
Loading...

Input

10 2

Expected Output

1010