Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a ushort value into two byte values in C#

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?

like image 857
user2071938 Avatar asked Sep 03 '13 08:09

user2071938


1 Answers

Use BitConverter

var bytes = BitConverter.GetBytes(package.FrameID);
like image 121
EZI Avatar answered Nov 03 '22 00:11

EZI