Convert a ushort value into two byte values in C#

家住魔仙堡 提交于 2019-12-20 04:34:48

问题


How do I split a ushort into two byte variables in C#?

I tried the following (package.FrameID is ushort):

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);

In my case package.FrameID is 56 and the result in array[0] is 16 instead of 56.

How can I fix this?


回答1:


0x0000000011111111 is not a binary number, it's a hex number. You need to use 0x0ff instead.

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);

(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.)




回答2:


Use BitConverter

var bytes = BitConverter.GetBytes(package.FrameID);


来源:https://stackoverflow.com/questions/18587611/convert-a-ushort-value-into-two-byte-values-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!