How does this unsafe code work?

I read the book C.Sharp 3.0 in a Nutshell and met the following code snippet that interested me.

  unsafe void RedFilter(int[,] bitmap)
    {
      int length = bitmap.Length;
      fixed (int* b = bitmap)
      {
        int* p = b;
        for(int i = 0; i < length; i++)
          *p++ &= 0xFF;
      }
    }

Can someone explain to me how this "* p ++ & = 0xFF" works?

+5
source share
5 answers

It is assumed that the function is designed to obtain a bitmap image and filter all colors except red.

, 32- , int. , p ( int), ANDing 0xFF, ( , ). int ( ++). ?

+9

(IMO *p++ &= 0xFF; - , ):

*p = *p & 0xFF;
p++;

, a = a & 0xFF, , 8 a.

+6

, C, , . :

int temp = *p;
temp = temp & 0x000000ff;
*p = temp;
p = p + 1;   // Move pointer by 4 bytes.

, . . .

+2

p, , , , BMP ( , ) BGR,

, .

+1

, , ,

x &= y

x = x y

An 'int' '0xff' 3 ().

askterisk ,

*p

- .

"Act" updates the actual value of the pointer, indicating the next integer in memory.

Thus, in the general case, the code will go through integers of length in memory and mask everything except the low byte (that is, the “red” byte if it is [A] BGR color values).

+1
source

All Articles