Unclear about using bitwise and assignment

Recently, I looked at some project in C ++ and tried to find out some of its principles of work on the project. I am a bit unclear regarding the use of the bitwise AND operator.

I can’t ask him, so I thought maybe someone here can help me ...

There is an unsigned variable int X = 0; , it always increases by "1" in the while loop.

while (...) { ... some code ... X++; X &= (1024 - 1); } 

I really don't understand the use of " & = ", what could be the purpose of such use?

Thanks.

+6
source share
4 answers

1024 - 1 is 1023 , which is 1111111111 in binary format

X &= Y means X = X & Y ;

So that means X = X & (binary) 1111111111

That will mask everything except the ten least significant bits.

This will make X wrap around from 0 to 1023 (but this is not the same as just dropping X to zero, as it will handle any overflow)

+10
source

&= and ++ together coincide with X = (X + 1) % 1024; but can be faster computed by the processor.


1024-1 is 11 1111 1111 in binary, so for numbers where X < 1024 , bitwise AND will have no effect (since any bit and 1 = the same bit). Interesting things begin to happen only where X β‰₯ 1024, so consider a loop iteration where X starts at 1023.

 X++; // X= 100 0000 0000 X &= 1024-1; // & 11 1111 1111 // so, X=0. 

In the context, then what happens, X increases from 0 to 1023, and then returns to 0. You can see that this happens with much smaller numbers in the next test program. To make it easier to see, I use 4 (different power 2) instead of 1024.

 #include <iostream> int main () { unsigned int x = 0; for (int ii = 0; ii < 10; ++ii) { x++; x &= (4-1); std::cout << "loop iteration #" << ii << ": x=" << x << std::endl; } return 0; } /* expected output: loop iteration #0: x=1 loop iteration #1: x=2 loop iteration #2: x=3 loop iteration #3: x=0 loop iteration #4: x=1 loop iteration #5: x=2 loop iteration #6: x=3 loop iteration #7: x=0 loop iteration #8: x=1 loop iteration #9: x=2 */ 
+14
source

In this case, the number will never be more than 1023.

In binary format X will be:

 0000000000 0000000001 0000000010 0000000011 etc. 

So, when you execute bitwise AND from 1023 (1111111111), only the least significant 10 bits remain.

+3
source
 X &= (1024 - 1); 

is an

 X = X & 1023 

and all the first bits of 10 remain (1023 is 1111111111 binary) and sets the rest to 0 .

In a loop it is useful to make sure that X will not exceed 1023 , a simple code is:

 while (...) { ... some code ... X++; X = X % 1024; // more closely resembles the original intent } 
+3
source

Source: https://habr.com/ru/post/956714/


All Articles