左位转移255(作为一个字节) [英] Left bit shifting 255 (as a byte)

查看:332
本文介绍了左位转移255(作为一个字节)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何人都可以解释为什么以下不编译?

Can anyone explain why the following doesn't compile?

byte b = 255 << 1

错误:

恒值'510'不能被转换为字节

Constant value '510' cannot be converted to a 'byte'

我期待在二元以下内容:

I'm expecting the following in binary:

1111 1110

该类型转换难倒我了。

The type conversion has stumped me.

推荐答案

在C#数字文本是 INT ,而不是字节(和位移位将被由编译器进行评价的,因此只有510遗体)。因此,您尝试将值赋给字节不适合。你可以用255面膜:

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:

byte b = (255 << 1) & 0xFF

再次降低结果为8位。与Java,C#不允许通过溢出未被发现去。基本上,你有两个选择明智试图分配510字节时:要么在最大值钳,那么你会得到255,或者扔掉不适合位,在这种情况下,你会得到254。

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.

您也可以使用选中,作为<一个href=\"http://stackoverflow.com/questions/737781/left-bit-shifting-255-as-a-byte/737810#737810\">lassevk上述:

byte b = unchecked((byte)(255 << 1));

这篇关于左位转移255(作为一个字节)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆