سؤال

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);
هل كانت مفيدة؟

المحلول

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

نصائح أخرى

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     

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

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.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top