Convert a ushort value into two byte values in C#

前端 未结 2 943
無奈伤痛
無奈伤痛 2021-01-23 02:18

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 ge

2条回答
  •  北海茫月
    2021-01-23 02:54

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

提交回复
热议问题