简体   繁体   English

>>操作符在C#中做什么?

[英]What does the >> operator do in C#?

I'm quite new to C# and trying to do a basic image processing software. 我对C#很陌生并试图做一个基本的图像处理软件。 I understand this snippet extracts A,R,G,B from an ARGB int value of a WriteableBitmap pixel "current" 我理解这个片段从WriteableBitmap像素“当前”的ARGB int值中提取A,R,G,B

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? 另外,如果我单独对r,g和b进行一些计算,如何将它们转换回整数ARGB值以用新的像素替换原始像素?

Thanks in advance. 提前致谢。

Edit: thanks guys, it makes sense now. 编辑:谢谢你们,现在有道理。

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): 如果您有一个由(a,r,g,b)定义的颜色,它的二进制表示将如下所示(假设通道深度为8位):

AAAAAAAA RRRRRRRR GGGGGGGG BBBBBBBB

So, shift that whole thing over 24 places and you are left with the alpha channel 所以,将整个事物转移到24个地方,你就会留下alpha通道

AAAAAAAA

Shift by 16 and you get the alpha channel and the red channel 移动16,你得到alpha通道和红色通道

AAAAAAAARRRRRRRR

Now, since that is cast as a byte, only the first 8 bits are extracted 现在,由于它被转换为字节,因此只提取前8位

(byte)AAAAAAAARRRRRRRR == RRRRRRRR

You could also get the red channel by shifting 16 places and AND'ing with 11111111 (0xFF) 您还可以通过移动16个位置获得红色通道,并使用11111111(0xFF)进行AND运算

AAAAAAAARRRRRRRR &
0000000011111111
----------------
00000000RRRRRRRR

It is shifting the bits of the current value to the right. 它将current值的位移到右侧。 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. 在这个特定代码snippit的情况下,它似乎是从所选位图数组元素中将每个字节的颜色信息提取成单独的颜色字节。

http://msdn.microsoft.com/en-us/library/xt18et0d.aspx 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,要将计算值返回到数组元素中,你可以反转位移过程并将结果重新组合在一起,如下所示:

int current = (alpha << 24) | (red << 16) | (green << 8) | blue; 

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: (按位OR)运算符:

int combined = (alpha << 24) | (red << 16) | (green << 8) | blue;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM