Question from the bit screening site

Here is the code:

unsigned int v;  // word value to compute the parity of
v ^= v >> 16;
v ^= v >> 8;
v ^= v >> 4;
v &= 0xf;
return (0x6996 >> v) & 1;

It calculates the parity of the word v. What is the meaning of 0x6996?

The number 0x6996 in binary format 110100110010110.

+3
source share
2 answers

Well, the algorithm compresses a 32-bit int into a 4-bit value of the same parity by consecutive bitwise ORs, and then ANDing with 0xf, so that the least significant 4-bits have only positive bits. In other words, after line 5, there vwill be an int between 0 and 15 inclusive.

Then it shifts this magic number ( 0x6996) to the right with this value 0-16 and returns only the least significant bit ( & 1).

, v 0x6996 1, 1, 0 - , 5 v 2, `, 3, 0.

+1

v 4- ( 0 15), , . 16- 0x6996 0 15, . :

//This array contains the parity of the numbers 0 to 15
char parities[16] = {0,1,1,0,1,0,0,1,1,0,0,1,0,1,1,0};
return parities[v];

, 0x6996. (0x6996 >> v) & 1 , .

+8

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


All Articles