How do I convert an int to two bytes in C#?
How do I convert an int to 开发者_如何转开发two bytes in C#?
Assuming you just want the low bytes:
byte b0 = (byte)i,
b1 = (byte)(i>>8);
However, since 'int' is 'Int32' that leaves 2 more bytes uncaptured.
You can use BitConverter.GetBytes to get the bytes comprising an Int32. There will be 4 bytes in the result, however, not 2.
Is it an int16?
Int16 i = 7;
byte[] ba = BitConverter.GetBytes(i);
This will only have two bytes in it.
Another way to do it, although not as slick as other methods:
Int32 i = 38633;
byte b0 = (byte)(i % 256);
byte b1 = (byte)(i / 256);
Option 1:
byte[] buffer = BitConverter.GetBytes(number);
Option 2:
byte[] buffer = new byte[2];
buffer[0] = (byte) number;
buffer[1] = (byte)(number >> 8);
I prefer option 1!
精彩评论