Convert Decimal Number to Binary or Hex Without itoa function

Code

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

void print_base(uint16_t num, uint8_t base) {
    // Your logic here
    char str[20];
    int first_one_found = 0, index = 0, number = 0;
    if(num==0)
    {
        printf("%hu", num);
        return;
    }
    if(base==2)
    {
        for(uint8_t i=0; i<16; i++)
        {
            if(!first_one_found)
            {
                if(!(((num >> (15-i)) & 1)))
                    continue;
                else
                {
                    first_one_found = 1;
                    str[index++] = ((num >> (15-i)) & 1) + '0';
                }
            }
            else
                str[index++] = ((num >> (15-i)) & 1) + '0';
        }
        
        str[index] = '\0'; 
        printf("%s", str);
    }
    else if(base==16)
    {
        for(uint8_t i=0; i<4; i++)
        {
            if(!first_one_found)
            {
                if(!(((num >> (12-4*i)) & 15)))
                    continue;
                else
                {
                    first_one_found = 1;
                    number = ((num >> (12-4*i)) & 15);
                    str[index++] = (number < 10) ? (number + '0'): (number + 'A' - 10);
                }
            }
            else
            {
                number = ((num >> (12-4*i)) & 15);
                str[index++] = (number < 10) ? (number + '0'): (number + 'A' - 10);
            }
        }
        if(index==0)
            str[index++] = '0';
        str[index] = '\0'; 
        printf("%s", str);
    }
}

int main() {
    uint16_t num;
    uint8_t base;
    scanf("%hu %hhu", &num, &base);

    print_base(num, base);
    return 0;
}

Solving Approach

 

 

 

Upvote
Downvote
Loading...

Input

10 2

Expected Output

1010