说明:C#?BitConverter 字节数组byte[ ] 转各种数据类型用法示例
byte[] bytes = { 1, 0 };
bool result = BitConverter.ToBoolean(bytes, 0); // 输出:true
byte[] bytes = { 65, 66 };
char result = BitConverter.ToChar(bytes, 0); // 输出:'A'
byte[] bytes = { 0xFF, 0x7F };
short result = BitConverter.ToInt16(bytes, 0); // 输出:-129
byte[] bytes = { 0xFF, 0xFF, 0xFF, 0x7F };
int result = BitConverter.ToInt32(bytes, 0); // 输出:-1
byte[] bytes = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x7F };
long result = BitConverter.ToInt64(bytes, 0); // 输出:-1
byte[] bytes = { 0x41, 0x48, 0x00, 0x00 };
float result = BitConverter.ToSingle(bytes, 0); // 输出:12.5
byte[] bytes = { 0x40, 0x24, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
double result = BitConverter.ToDouble(bytes, 0); // 输出:10.0
byte[] bytes = { 72, 101, 108, 108, 111 };
string result = BitConverter.ToString(bytes, 0, 5); // 输出:"48-65-6C-6C-6F"
byte[] bytes = { 0x01, 0x02 };
ushort value = BitConverter.ToUInt16(bytes, 0);
Console.WriteLine(value); // 输出:258
ushort value = 258;
byte[] bytes = BitConverter.GetBytes(value);
Console.WriteLine(BitConverter.ToString(bytes)); // 输出:01-02
byte[] bytes = { 0x41,0x42, 0x43 };
string str = BitConverter.ToString(bytes);
Console.WriteLine(str); // 输出:41-42-4312.
string str = "41-42-43";
string[] strArray = str.Split('-');
byte[] bytes = new byte[strArray.Length];
for (int i = 0; i < strArray.Length; i++)
{
bytes[i] = Convert.ToByte(strArray[i], 16);
}
Console.WriteLine(BitConverter.ToString(bytes)); // 输出:41-42-43
int value = 123;
byte[] bytes = BitConverter.GetBytes(value);
Console.WriteLine(BitConverter.ToString(bytes)); // 输出:7B-00-00-00
byte[] bytes = { 0x7B, 0x00, 0x00, 0x00 };
int value = BitConverter.ToInt32(bytes, 0);
Console.WriteLine(value); // 输出:123