What is the function of bitwise & in this statement?

I read about the implementation of the diamond square algorithm in C #, which wraps around to create seamless textures. To calculate the next point, on average, four sample points located in a square or diamond are taken. If the dot pattern lies on the edge of the texture, it is wrapped around the other side. This packaging seems to be done using the following method:

public double sample(int x, int y) { return values[(x & (width - 1)) + (y & (height - 1)) * width]; } 

A little research tells me this is a bitwise operator. I have not used them before, and the Wikipedia article was not enlightening. Can someone explain what the & operator does in this method?

EDIT: texture sizes are always equal to two

+5
source share
1 answer

This is for the "wrap". Assuming width and height are powers of two (otherwise it won't work, so it's better to be true), x & (width - 1) is basically equivalent to x % width , except that it also works for negative x (whereas x % width with negative x will have a negative result) and almost certainly faster.

Or to visually display an example, for example width = 64 and x = 64+12 = 76 , then

 x = 00000000 00000000 00000000 01001100 w = 00000000 00000000 00000000 01000000 w-1 = 00000000 00000000 00000000 00111111 x & w-1 = 00000000 00000000 00000000 00001100 = 12 

As you can see from form w-1 , the operation x & w-1 is similar to executing only the lower bits of x , assuming, of course, that w is still a power of two. Thus, bits with weights 64 and multiples of 64 are deleted in the same way as the true β€œmodulo 64” operation (which is not % in C #, if you work with integer signs, this is the remainder).

+8
source

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


All Articles