Reputation: 101
I'm quite new to C# and trying to do a basic image processing software. I understand this snippet extracts A,R,G,B from an ARGB int value of a WriteableBitmap pixel "current"
for(int i = 0; i < bitmapArray.Length; i++) {
var current = bitmapArray[i];
var alpha = (byte)(current >> 24);
var red = (byte)(current >> 16);
var green = (byte)(current >> 8);
var blue = (byte)(current);
//Some code
}
What is ">>" doing to convert the values?
Also, If I do some calculations to the r,g and b individually, how do I convert them back to an integer ARGB value to replace the original pixel with the new one?
Thanks in advance.
Edit: thanks guys, it makes sense now.
Upvotes: 10
Views: 539
Reputation: 124722
It is the binary shift operator.
If you have a color defined by (a, r, g, b), it's binary representation would look like this (assuming a channel depth of 8 bits):
AAAAAAAA RRRRRRRR GGGGGGGG BBBBBBBB
So, shift that whole thing over 24 places and you are left with the alpha channel
AAAAAAAA
Shift by 16 and you get the alpha channel and the red channel
AAAAAAAARRRRRRRR
Now, since that is cast as a byte, only the first 8 bits are extracted
(byte)AAAAAAAARRRRRRRR == RRRRRRRR
You could also get the red channel by shifting 16 places and AND'ing with 11111111 (0xFF)
AAAAAAAARRRRRRRR &
0000000011111111
----------------
00000000RRRRRRRR
Upvotes: 16
Reputation: 180858
It is shifting the bits of the current
value to the right. In the case of this particular code snippit, it appears to be extracting each byte of color information from the selected bitmap array element into individual color bytes.
http://msdn.microsoft.com/en-us/library/xt18et0d.aspx
Assuming that your array contains ints, to get a computed value back into the array element, you would reverse the bit-shifting process and OR the results back together, like so:
int current = (alpha << 24) | (red << 16) | (green << 8) | blue;
Upvotes: 12
Reputation: 269498
Further to Robert's answer -- and to cover the second part of your question -- you can combine the separate components back to an integer using the <<
(left-shift) and |
(bitwise OR) operators:
int combined = (alpha << 24) | (red << 16) | (green << 8) | blue;
Upvotes: 2