Search code examples
cbitbitmask

Converting from decimal to base 4 using bitmasking


I'm trying to write a program that converts from decimal to base 4 using bit masking. First I wrote this program that converts from decimal to binary to understand how it works

#include <stdio.h>
void binary(unsigned int num) {   
    int i;                                                                          
    unsigned temp, mask=1;                    
    mask<<=31;                       
    for(i=0; i<32; i++) {     
        temp=num&mask;                  
        printf("%d", temp>>(31-i));
        mask>>=1;
    }
}
int main () {
    int n;
    printf("Enter a number:\n");
    scanf("%d", &n);
    binary(n);
    return 0;
}

Then I was trying to use the same approach here

void base4(unsigned int num) {   
    int i;                                                                          
    unsigned temp, mask=3;                    
    mask<<=15;                       
    for(i=0; i<16; i++) {     
        temp=   // <<<==== ???               
        printf("%d", temp>>(15-i)*2);
        mask>>=1;
    }

I know that in in base 4, numbers use 2 bits. So if we are ANDing each bit of a given value lets say 22 with the corresponding bit of the mask=3 we will end up with something like this

.... 0  0  1  1  2  (base4)
.... 00 00 01 01 10 (bin)

I just couldn't use this information to apply it to my previous approach, would be great if someone could help.


Solution

  • char *toBase4(char *buff, unsigned val, int printZeroes)
    {
        char *wrk = buff;
        int shift = sizeof(val) * CHAR_BIT - 2;
        unsigned mask = 3 << shift;
    
        do
        {
            if((val & mask) || printZeroes) 
            {
                *wrk++ = ((val & mask) >> shift) + '0';
                printZeroes = 1;
            }
            mask >>= 2;
        }while((shift -= 2) >= 0);
        *wrk = 0;
        return buff;
    }
    
    int main(void)
    {
        char x[256];
    
        printf("%s\n", toBase4(x, 0xff00, 0));
        printf("%s\n", toBase4(x, 0xff00, 1));
    }