[英]How do I convert an int to two bytes in C#?
如何在C#中將int轉換為兩個字節?
假設你只想要低字節:
byte b0 = (byte)i,
b1 = (byte)(i>>8);
但是,因為'int'是'Int32',所以剩下2個字節未被捕獲。
您可以使用BitConverter.GetBytes來獲取包含Int32的字節。 結果中將有4個字節,但不是2。
另一種方法,雖然不像其他方法那樣光滑:
Int32 i = 38633;
byte b0 = (byte)(i % 256);
byte b1 = (byte)(i / 256);
是int16嗎?
Int16 i = 7;
byte[] ba = BitConverter.GetBytes(i);
這只有兩個字節。
選項1:
byte[] buffer = BitConverter.GetBytes(number);
選項2:
byte[] buffer = new byte[2];
buffer[0] = (byte) number;
buffer[1] = (byte)(number >> 8);
我更喜歡選項1!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.