Convert Decimal Number to Binary or Hex Without itoa function

Code

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

uint64_t power(int num, int exp)
{
    uint64_t result = 1;
    while(exp--)
    {
        result *= num;
    }
    return result;
}

void print_base(uint16_t num, uint8_t base) {
    // Your logic here
   char hexValues[] = "0123456789ABCDEF";
    uint16_t temp = num;
    char buffer[255] = {0};
    int count =0;
    uint64_t result = 0;
    if(base == 16)
    {
        while(temp)
        {
            uint16_t t = temp % 16;
            buffer[count++] = hexValues[t];
            temp /= 16;
        }
        
        for(int i=0; i<count; ++i)
        {
            printf("%c",buffer[count-1-i]);
        }   
    }
    
    else if(base == 2)
    {
        int exp = 0;
        while(temp)
        {
            uint16_t t = temp %2;
            result += t*power(10,exp);
            exp++;
            temp /= 2;
        }
        printf("%llu",result);
    }
}

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