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 j,i,val;
    char str[16];
    if(num==0)
    printf("%d",num);
    else
    {
        while(num>0)
        {
            val=num%base;
            if(val<10)
            {
            str[i++]=val+'0';
            }
            else{
                str[i++]=(val-10)+'A';
            }
            num/=base;

            
        }
        for(j=i-1;j>=0;j--)
        {
            printf("%c",str[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