简体   繁体   English

使用位掩码从十进制转换为基数 4

[英]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.我正在尝试编写一个使用位掩码从十进制转换为基数 4 的程序。 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.我知道在基数 4 中,数字使用 2 位。 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因此,如果我们对给定值的每一位进行 AND 运算,让我们说 22 与mask=3的相应位,我们最终会得到类似这样的结果

.... 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.我只是无法使用此信息将其应用于我以前的方法,如果有人可以提供帮助,那就太好了。

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));
}

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM