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) {
    char result[17] = "0000000000000000";
    uint16_t tmp=num;
    uint8_t i = 15;
    if (num==0) putchar('0');
    else{
    while(tmp>0){
        uint16_t val = tmp%base;
        if(val>9) result[i] = 'A'-10+val;
        else result[i] = '0'+val;
        tmp/=base;
        i--;
        }
        for(int j=i+1;result[j]!='\0';j++) putchar(result[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