How am I getting a single bit from an int?

浪子不回头ぞ 提交于 2019-12-08 12:54:41

问题


I understand that:

int bit = (number >> 3) & 1;

Will give me the bit 3 places from the left, so lets say 8 is 1000 so that would be 0001.

What I don't understand is how "& 1" will remove everything but the last bit to display an output of simply "1". I know that this works, I know how to get a bit from an int but how is it the code is extracting the single bit?

Code...

int number = 8;
int bit = (number >> 3) & 1;
Console.WriteLine(bit);

回答1:


Unless my boolean algebra from school fails me, what's happening should be equivalent to the following:

              *
  1100110101101  // last bit is 1
& 0000000000001  // & 1
= 0000000000001  // = 1

              *
  1100110101100  // last bit is 0
& 0000000000001  // & 1
= 0000000000000  // = 0

So when you do & 1, what you're basically doing is to zero out all other bits except for the last one which will remain whatever it was. Or more technically speaking you do a bitwise AND operation between two numbers, where one of them happens to be a 1 with all leading bits set to 0




回答2:


8      = 00001000
8 >> 1 = 00000100
8 >> 2 = 00000010
8 >> 3 = 00000001


If you use mask 1 = 000000001 then you have:
8 >> 3       = 000000001
1            = 000000001
(8 >> 3) & 1 = 000000001     



回答3:


Actually this is not hard to understand. the "& 1" operation is just set all bits of the value to the "0", except the bit, which placed in the same position as the valuable bit in the value "1"

previous operation just shifts the all bits to the right. and places the checked bit to the position which won't be setted to "0" after operation "& 1"

fo example

number is 1011101

number >> 3 makes it 0001011

but (number >> 3) & 1 makes it 0000001




回答4:


When u right shift 8 you get 0001
0001 & 0001 = 0001 which converted to int gives you 1.

So, when a value 0001 has been assigned to an int, it will print 1 and not 0001 or 0000 0001. All the leading zeroes will be discarded.



来源:https://stackoverflow.com/questions/21878434/how-am-i-getting-a-single-bit-from-an-int

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!