[英]How do I convert an int to two bytes in C#?
如何在C#中将int转换为两个字节?
假设你只想要低字节:
byte b0 = (byte)i,
b1 = (byte)(i>>8);
但是,因为'int'是'Int32',所以剩下2个字节未被捕获。
您可以使用BitConverter.GetBytes来获取包含Int32的字节。 结果中将有4个字节,但不是2。
另一种方法,虽然不像其他方法那样光滑:
Int32 i = 38633;
byte b0 = (byte)(i % 256);
byte b1 = (byte)(i / 256);
是int16吗?
Int16 i = 7;
byte[] ba = BitConverter.GetBytes(i);
这只有两个字节。
选项1:
byte[] buffer = BitConverter.GetBytes(number);
选项2:
byte[] buffer = new byte[2];
buffer[0] = (byte) number;
buffer[1] = (byte)(number >> 8);
我更喜欢选项1!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.