Home > Blockchain >  "0xFFFF &" in array index, what does this mean?
"0xFFFF &" in array index, what does this mean?

Time:02-04

I saw something like

somearray[0xFFFF & bi]

in a C /CUDA code, I wonder what does this mean?

CodePudding user response:

In general, the operations x % y and x & (y-1) are equivalent if y is a power of two.

This is the case for your code snipped. Thus, somearray[0xFFFF & bi] is equivalent to somearray[bi % 65536] which means only the first 65536 array entries will be accessed, but with wrap-around for values of bi which are larger than 65535.

The computation of a bitwise AND is more efficient than plain modulo computation. However, modern compilers should perform this transformation automatically if the righthanded side of modulo is a power of two compile-time constant. I would prefer writing x % 65536 for readability.

CodePudding user response:

The index of the array (somearray) will be calculated as follows:

  1. 0xFFFF equals 65535 decimal, which equals 16 times binary 1s (1111111111111111)
  2. your bi variable will also be 'represented' in binary
  3. The two will be ANDed together and you have your index calculated. If bi is less then 16 bit integer, then the index will equal bi, or else, it will be the lesser 16 bit of bi - or else, if it is not of type integer, you will get compiler error.

CodePudding user response:

This means:

use low 16 bits of bi as somearray 's index.

  •  Tags:  
  • Related