116. Convert Decimal Number to Binary or Hex Without itoa function

Back To All Submissions
Previous Submission
Next Submission

Code

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

void print_base(uint16_t num, uint8_t base) {
    //1. Repeatedly find the LSB of the num, then remove LSB
    //How to find LSB? 
    //(num % base) gives remainder (LSB) 
    // 0 or 1 for base 2 
    // 0-15 for base 16

    //How to remove LSB?
    //(num /=base) removes LSB
    
    if(num==0){
        printf("0\n");
    }
    char hex[16] = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
    char output[20] = {};
    int i=0;
    while(num){
        output[i] = hex[(num % base)]; //hex[remainder of LSB] 
        num/= base; //Remove LSB
        i++;
    }

    //Print reversed array
    for(int j=i-1;j>=0;j--){
        printf("%c",output[j]);
    }
}

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

    print_base(num, base);
    return 0;
}

Solving Approach

 

 

 

Was this helpful?
Upvote
Downvote