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>

char hexdigits[16] = {'0', '1', '2', '3', '4', '5', '6', '7', 
                      '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };


void print_base(uint16_t num, uint8_t base) {
    // Your logic here
    uint16_t mask, nibble, digit;

    switch (base) {
        case 2:
        mask = 0x8000;
        if (num == 0) {
            printf("%c", '0');
            break;
        }
        // find leading one
        while ((mask & num) ==0) {
            mask = mask >> 1;
        }
        while (mask != 0) {
            if ((mask & num) == 0) 
                printf("%c", '0');
            else
                printf("%c", '1');
            mask = mask >> 1;
        }
        break;

        case 16:
        default:
        mask = 0xF000;
        nibble= 3;
        if (num == 0) {
            printf("%c", '0');
            break;
        }
        // find leading nibble
        while ((mask & num) ==0) {
            mask = mask >> 4;
            nibble--;
        }
        while (mask != 0) {
            if (mask & num == 0) 
                printf("%c", '0');
            else {
                digit = (mask & num) >> (nibble * 4);
                printf("%c", hexdigits[digit]);
            }
              
            mask = mask >> 4;
            nibble--;
        }


        break;
    }
}

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

    print_base(num, base);
    return 0;
}

Solving Approach

 

Create array for hex digits

Always test for zero

if in base 2, look for leading one

if in base 16, look for leading nibble

After locating leading one or nibble, use a sliding mask and 

detect non zero bits , or nibbles in base 16.

 

Was this helpful?
Upvote
Downvote