C# 左移右移在資料型別轉換中的使用

Qin_Wenwen發表於2020-10-31

關於如何將byte資料轉換為其他型別如uint或ushort型別,使用如下:

(注意大端小端)

  1. byte轉ushort 左移

byte[] buffer = { 0x05, 0x01 };

ushort number= (ushort)(((buffer [0] & 0xFF) << 8) | (buffer [1] & 0xFF));

  1. byte轉ushort BitConverter

byte[] buffer = { 0x01, 0x02 };

Array.Reverse(buffer);

ushort methodID = BitConverter.ToUInt16(buffer, 0);

//以上效果等同於左移使用

//用Converter可能需要反轉陣列,才能正確獲取值,具體情況需要你驗證。

  1. byte轉uint 左移

byte[] buffer = { 0x05, 0x01, 0x03, 0x04 };
 
uint number = (uint)(((buffer [0] & 0xFF) << 24) | (buffer [1] & 0xFF) << 16) | (buffer [2] & 0xFF) << 8) | (buffer [3] & 0xFF));

  1. ushort 轉byte 右移
ushort number;

byte[] buffer;

buffer[0] = (byte)((number >> 8) & 0xFF);

buffer[1] = (byte)((number >> 0) & 0xFF);

  1. uint 轉byte 右移
uint number;

byte[] buffer;

buffer[0] = (byte)((number >> 24) & 0xFF);

buffer[1] = (byte)((number >> 16) & 0xFF);

buffer[2] = (byte)((number >> 8) & 0xFF);

buffer[3] = (byte)((number >> 0) & 0xFF);

相關文章