I read the "C.Sharp 3.0 in a Nutshell" book and met the next piece of code, 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;
}
}
Could anyone explain me how does this "*p++ &= 0xFF" work?
Unsafe code can be used in Visual Studio IDE by following the given steps: Double click properties in the Solution Explorer to open project properties. Click the Build tab and select the option “Allow Unsafe Code”.
Create a file in your <Project Path>/Assets directory and name it smcs. rsp then put -unsafe inside that file. Save and close that file. Close and reopen Visual Studio and Unity Editor.
Unsafe code in C# isn't necessarily dangerous; it's just code whose safety cannot be verified. Unsafe code has the following properties: Methods, types, and code blocks can be defined as unsafe. In some cases, unsafe code may increase an application's performance by removing array bounds checks.
In general, the code that we write in C# is safe code. It creates managed objects and doesn't access the memory directly. On the other hand, unsafe code in C# is code that is not in direct control of the Common Language Runtime (CLR).
The function is presumably meant to take a bitmap image, and filter out all the colors except red.
This assumes that it's a 32-bit bitmap, where each pixel is represented by an int
.
You're dereferencing the memory location currently pointed to by p
(which is an int
), and ANDing it with 0xFF
, which effectively leaves only the red component of the pixel (assuming that the lowest byte is the red component). You're also automatically incrementing the pointer to the next int
(with ++
). Does that answer it?
It's the same as this (IMO the original *p++ &= 0xFF;
trick is a little nasty -- it's one line of code that's doing two things):
*p = *p & 0xFF;
p++;
An expression like a = a & 0xFF
sets all but the bottom 8 bits of variable a
to zero.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With