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
    int arr[20];
    int i=0;
    char binary[]="01";
    char hexa[]="0123456789ABCDEF";
    if(num==0){
        printf("0");
    }
    while(num>0){
        arr[i]=num%base;
        num=num/base;
        i++;
    }
if(base==2){
    for(int j=i-1;j>=0;j--){
    printf("%c",binary[arr[j]]);
}
}
else if(base==16){
for(int j=i-1;j>=0;j--){
    printf("%c",hexa[arr[j]]);
}
}


}


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