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) {
    // Your logic here
    uint16_t pre = num;
    uint16_t tre =0;
    for(int i =0; i <16; i++){
        pre = num % 2;
        if(pre == 1){
            tre = tre | (1<<i);
        }
        num = num /2;
    }
    if(base == 2){
        printf("%b", tre);
    }else if(base == 16){
        printf("%X", tre);
    }
}

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