在C#中将ushort值转换为两个字节值 [英] Convert a ushort value into two byte values in C#
问题描述
如何在C#中将ushort分成两个字节变量?
How do I split a ushort into two byte variables in C#?
我尝试了以下操作(package.FrameID为ushort):
I tried the following (package.FrameID is ushort):
当我尝试使用纸和铅笔进行计算时,我得到了正确的结果.另外,如果FrameID大于一个字节(因此第二个字节不为零),则它可以工作.
When I try to calculate this with paper&pencil I get the right result. Also, if FrameID is larger than a byte (so the second byte isn't zero), it works.
array[0] = (byte)(0x0000000011111111 & package.FrameID);
array[1] = (byte)(package.FrameID >> 8);
在我的情况下,package.FrameID为56,array [0]中的结果为16而不是56.
In my case package.FrameID is 56 and the result in array[0] is 16 instead of 56.
我该如何解决?
推荐答案
0x0000000011111111
不是二进制数,而是一个十六进制数.您需要改用0x0ff
.
0x0000000011111111
is not a binary number, it's a hex number. You need to use 0x0ff
instead.
但是,由于结果是一个字节,并且强制转换为一个字节,无论如何都将丢弃高位,因此您实际上不需要and
结果.您可以这样做:
However, since the result is a byte and casting to a byte will discard the upper bits anyway, you don't actually need to and
the result. You can just do this:
array[0] = (byte)package.FrameID;
array[1] = (byte)(package.FrameID >> 8);
(这是假设您未使用checked
代码.如果是,则将大于255的值强制转换为byte
将导致异常.您将知道是否正在使用checked
代码.)
(That's assuming that you are not using checked
code. If you are, then casting a value greater than 255 to a byte
will cause an exception. You will know if you are using checked
code.)
这篇关于在C#中将ushort值转换为两个字节值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!