铸造成字节在C# [英] Casting to byte in C#

查看:184
本文介绍了铸造成字节在C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:结果
会发生什么,当你从短期转换为C#?



$字节b

$ b

有人能解释铸造值一个字节时发生了什么,如果它的最小/最大字节的范围之外?这似乎是取整数值,并与255,我试图理解为什么这并不抛出异常的原因模了。

  INT I = 5000; 
字节B =(字节)I;

Console.WriteLine(二); //输出136


解决方案

5000被表示为4个字节( INT)
(十六进制)



| 00 | 00 | 13 | 88 |



现在,当你将它转换为字节,它只是需要在最后1个字节



理由:在IL级别的conv.u1 运营商将被用来在发生转换的int字节溢出,这将截断高位。 (见 conv.u1 文档中的备注部分)。



| 88 |



这是136十进制表示


Possible Duplicate:
What happens when you cast from short to byte in C#?

Can someone explain what's happening when casting a value to a byte, if it's outside the range of min/max byte? It seems to be taking the integer value and modulo it with 255. I'm trying to understand the reason for why this doesn't throw an exception.

int i = 5000;
byte b = (byte)i;

Console.WriteLine(b);  // outputs 136

解决方案

5000 is represented as 4 bytes (int) (hexadecimal)

|00|00|13|88|

Now, when you convert it to byte, it just takes the last 1-byte.

Reason: At the IL level, conv.u1 operator will be used which will truncate the high order bits if overflow occurs converting int to byte. (See remarks section in the conv.u1 documentation).

|88|

which is 136 in decimal representation

这篇关于铸造成字节在C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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