简体   繁体   English

十进制到二进制的转换方法

[英]Decimal to Binary conversion method

I came across this method of conversion decimal numbers to binary: 我遇到了将十进制数字转换为二进制的这种方法:

int main(void){
    int i            = 0;
    unsigned int u_i = 0;
    int j            = 0;
    int b[16]        = {0}; //Assuming your integer size is 16bit

    printf("input number");
    scanf("%d",&i);

    u_i = (unsigned int)i;

    for(j=15;j>=0;j--) {
        b[j] = u_i & 0x1;
        u_i  = u_i >> 1;
    }

    for (j=0;j<=15;j++)
        printf("%d", b[j]);

    printf("\n");
    return 0;
}

I cannot understand the "0x1" part that is responsible for the conversion. 我无法理解负责转换的“ 0x1”部分。 Could anyone elaborate this? 有人可以详细说明吗? Thank you in advance. 先感谢您。

What is happening is something called a mask. 发生的事情是所谓的面具。 Basically what is going on is you have an unsigned integer of 16 bits. 基本上发生了什么,您有一个16位无符号整数。 Lets say we have the following: 可以说我们有以下内容:

uint x = 43981

this is equivalent in hex to 0xABCD 相当于十六进制的0xABCD

And in binary 1010101111001101 并以二进制1010101111001101

So in order to convert this into an array, what the algorithm is doing is saying: 因此,为了将其转换为数组,该算法正在做的事情是说:

Shift the bits over one spot to the right. 将位向右移动一个位置。

1010101111001101 >> 1 becomes 0101010111100110 1010101111001101 >> 1变为0101010111100110

which is all of the numbers moved to the right and a 0 is placed on the left. 将所有数字移到右侧,将0放在左侧。

Then in order to just get the least significant bit, the following is done: 然后,为了获得最低有效位,请执行以下操作:

0101010111100110 
&
0000000000000001
=
0000000000000000 
= 
0

Another example would be 另一个例子是

0101010111100111
&
0000000000000001
=
0000000000000001
=
1

Basically the & with just a 1 will make all of the other bits 0 no matter what, and then the one bit with a 1 will become the value of whatever bit is in the corresponding spot in the original number. 基本上,仅带1的&将使其他所有比特都变为0,然后,带有1的比特将成为原始编号中对应位置的任何比特的值。

This will keep happening, and the original number will continue to be right shifted, until all of the numbers have been cycled through, creating your array of 0s and 1s. 这将继续发生,并且原始数字将继续右移,直到所有数字都循环遍历,从而创建0和1的数组。

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

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