Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does this unsafe code work?

Tags:

c#

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?

like image 511
Aleksey Borodkin Avatar asked Aug 10 '10 15:08

Aleksey Borodkin


People also ask

How do I allow unsafe code?

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”.

How do I allow unsafe code unity?

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.

What is unsafe code in C sharp?

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.

What is safe and unsafe code in C#?

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).


2 Answers

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?

like image 90
Dmitry Brant Avatar answered Oct 04 '22 06:10

Dmitry Brant


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.

like image 45
Tim Robinson Avatar answered Oct 04 '22 04:10

Tim Robinson