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.
Bitwise Right shift operator >> is used to shift the binary sequence to right side by specified position.
The >> operator is a signed right shift operator and >>> is an unsigned right shift operator. The left operands value is moved right by the number of bits specified by the right operand.
When shifting an unsigned value, the >> operator in C is a logical shift. When shifting a signed value, the >> operator is an arithmetic shift.
The stream insertion and stream extraction operators also can be overloaded to perform input and output for user-defined types like an object. In C++, << is both the insertion operator and the left-shift operator. >> is the extraction operator and the right-shift operator.
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
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;
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