C# 左移 255(作为一个字节)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/737781/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Left bit shifting 255 (as a byte)
提问by Chris S
Can anyone explain why the following doesn't compile?
谁能解释为什么以下不能编译?
byte b = 255 << 1
The error:
错误:
Constant value '510' cannot be converted to a 'byte'
常量值“510”无法转换为“字节”
I'm expecting the following in binary:
我期待以下二进制:
1111 1110
The type conversion has stumped me.
类型转换难倒了我。
采纳答案by Joey
Numeric literals in C# are int
, not byte
(and the bit shift will be evaluated by the compiler, hence only the 510 remains). You are therefore trying to assign a value to a byte
which does not fit. You can mask with 255:
C# 中的数字文字是int
,不是byte
(并且位移位将由编译器计算,因此只剩下 510)。因此,您试图为byte
不合适的a 分配一个值。您可以使用 255 进行屏蔽:
byte b = (255 << 1) & 0xFF
to reduce the result to 8 bits again. Unlike Java, C# does not allow overflows to go by undetected. Basically you'd have two sensible options when trying to assign 510 to a byte: Either clamp at the maximum value, then you'd get 255, or throw away the bits that do not fit, in which case you'd get 254.
再次将结果减少到 8 位。与 Java 不同,C# 不允许未检测到的溢出。基本上,在尝试将 510 分配给一个字节时,您有两个明智的选择:要么钳制最大值,然后得到 255,要么丢弃不适合的位,在这种情况下,您将得到 254。
You can also use unchecked
, as lassevk mentioned:
你也可以使用unchecked
,正如lassevk 提到的:
byte b = unchecked((byte)(255 << 1));
回答by Otávio Décio
255 << 1
will give you more than one byte.
会给你不止一个字节。
回答by Daniel A. White
have you tried casting it?
你试过铸造它吗?
byte b = (byte)(255 << 1)
This is an interesting approach - the above code will work if wrapped in a unchecked
block like this:
这是一个有趣的方法 - 如果包裹在这样的unchecked
块中,上面的代码将起作用:
unchecked
{
byte b = (byte)(255 << 1);
}
Since it is unchecked
the value is truncated to the intended value of 254. So it is possible to do this with a cast!
由于它unchecked
的值被截断为预期值 254。因此可以通过强制转换来做到这一点!
回答by Steve
You are shifting 255 by 1 bit, then trying to assign it to a byte.
255 << 1 is 510
, and 510 won't fit in to a byte.
您将 255 移动 1 位,然后尝试将其分配给一个字节。
255 << 1 is 510
, 并且 510 不适合一个字节。
回答by Michael Burr
byte b = 0xff & (255 << 1);
回答by Lasse V. Karlsen
The result of the <<
operator is an Int32
, not what you put into it.
<<
运算符的结果是Int32
,而不是您放入其中的内容。
You need to cast the result of the shift, not the input. Additionally, it will produce an overflow (it is larger than a byte afterall), so you need to specify that you need an unchecked cast.
您需要转换转换的结果,而不是输入。此外,它会产生溢出(毕竟它大于一个字节),因此您需要指定您需要未经检查的强制转换。
In other words, this will work:
换句话说,这将起作用:
Byte b = unchecked((Byte)(255 << 1));
回答by sipwiz
And since << has a higher precedence than & you can save the brackets:
由于 << 的优先级高于 & 您可以保存括号:
byte b = 255 << 1 & 0xff;