左移 255 位(作为一个字节)
谁能解释为什么以下内容无法编译?
byte b = 255 << 1
错误:
常量值“510”无法转换为“字节”
我期待二进制形式的以下内容:
1111 1110
类型转换困扰了我。
Can anyone explain why the following doesn't compile?
byte b = 255 << 1
The error:
Constant value '510' cannot be converted to a 'byte'
I'm expecting the following in binary:
1111 1110
The type conversion has stumped me.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
C# 中的数字文字是
int
,而不是byte
(位移位将由编译器计算,因此仅保留 510)。 因此,您尝试将一个值分配给不适合的byte
。 您可以使用 255: 进行掩码,以将结果再次减少到 8 位。 与 Java 不同,C# 不允许溢出未被检测到。 基本上,当尝试将 510 分配给一个字节时,您有两个明智的选择:要么限制在最大值,然后您将得到 255,要么丢弃不适合的位,在这种情况下您将得到 254。
您还可以使用
未选中
,如 lassevk 提到:Numeric literals in C# are
int
, notbyte
(and the bit shift will be evaluated by the compiler, hence only the 510 remains). You are therefore trying to assign a value to abyte
which does not fit. You can mask with 255: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.
You can also use
unchecked
, as lassevk mentioned:您将 255 移位 1 位,然后尝试将其分配给一个字节。
<代码> 255 << 1 是 510,而 510 无法容纳在一个字节中。
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.<<
运算符的结果是一个Int32
,而不是您放入其中的内容。您需要转换移位的结果,而不是输入。 此外,它会产生溢出(它毕竟大于一个字节),因此您需要指定您需要未经检查的强制转换。
换句话说,这将起作用:
The result of the
<<
operator is anInt32
, not what you put into it.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:
你尝试过铸造它吗?
这是一种有趣的方法 - 如果将上面的代码包装在
unchecked
块中,如下所示:由于它是
unchecked
,因此该值将被截断为预期值 254。通过演员阵容可以做到这一点!have you tried casting it?
This is an interesting approach - the above code will work if wrapped in a
unchecked
block like this:Since it is
unchecked
the value is truncated to the intended value of 254. So it is possible to do this with a cast!会给你多于一个字节。
will give you more than one byte.
并且自从<< 优先级高于 & 您可以保存括号:
And since << has a higher precedence than & you can save the brackets: