C# 字节 和 Int16整型 转换
Int16:硬件通信的「16 位寄存器」是行业主流
1. 整型 转 高低字节
/// <summary> /// 将整数转换为高字节在前,低字节在后的字节数组 /// </summary> static byte[] IntToHighLowBytes(int value) { if (value < 0 || value > 0xFFFF) throw new ArgumentException("数值超出范围"); return new byte[] { (byte)(value >> 8), (byte)(value & 0xFF) }; }
2. 整型 转 低高字节
/// <summary> /// 将整数转换为低字节在前,高字节在后的字节数组 /// </summary> static byte[] IntToLowHighBytes(int value) { // 检查数值是否在有效范围内(0 到 65535) if (value < 0 || value > 0xFFFF) throw new ArgumentException("数值超出范围"); // 返回低字节和高字节,低字节在前,高字节在后 return new byte[] { (byte)(value & 0xFF), (byte)(value >> 8) }; }
3. 高低字节 转 整型
/// <summary> /// 将大端排序的字节(高字节在前,低字节在后)转换回整数 /// </summary> static int HighLowBytesToInt(byte highByte, byte lowByte) { // 将高字节左移8位,再加上低字节,得到完整的整数 return (highByte << 8) | lowByte; }
PS: var buffer_R = Array.Reverse(buffer); //先反转
int32 = BitConverter.ToInt32(buffer_R , X); //从数组中的第X个开始读8个字节
4. 低高字节 转 整型
/// <summary> /// 将小端排序的字节(低字节在前,高字节在后)转换回整数 /// </summary> static int LowHighBytesToInt(byte lowByte, byte highByte) { // 将低字节直接作为整数的低8位,高字节左移8位作为高8位 return (lowByte) | (highByte << 8); }
PS: int32 = BitConverter.ToInt32(buffer, X); //从字节数组中第X个开始读8字节
PS: 字节数组 转 结构体
public static T ByteArrayToStructure<T>(byte[] bytes) where T : struct { GCHandle handle = GCHandle.Alloc(bytes, GCHandleType.Pinned); try { return Marshal.PtrToStructure<T>(handle.AddrOfPinnedObject()); } finally { handle.Free(); } }

浙公网安备 33010602011771号