How do I convert an int to two bytes in C#?

自闭症网瘾萝莉.ら 提交于 2021-02-18 22:16:05

问题


How do I convert an int to two bytes in C#?


回答1:


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.




回答2:


You can use BitConverter.GetBytes to get the bytes comprising an Int32. There will be 4 bytes in the result, however, not 2.




回答3:


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



回答4:


Is it an int16?

Int16 i = 7;
byte[] ba = BitConverter.GetBytes(i);

This will only have two bytes in it.




回答5:


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!



来源:https://stackoverflow.com/questions/3919804/how-do-i-convert-an-int-to-two-bytes-in-c

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