将整型int数字转化为byte数组

### C# 中将 byte 数组转换为数字的方法 在 C# 中,可以使用 `BitConverter` 类将 byte 数组转换为各种类型的数字。以下是一些常见的转换方法和代码示例。 #### 1. 将 byte 数组转换为 `ushort`(无符号短整型) ```csharp byte[] array = new byte[] { 0x02, 0x01 }; ushort register = BitConverter.ToUInt16(array, 0); // 结果为 258 ``` 这里使用了 `BitConverter.ToUInt16` 方法,从指定的索引位置开始读取两个字节并将其转换为一个 `ushort` 值[^2]。 #### 2. 将 byte 数组转换为 `int`(整型) ```csharp byte[] byteArray = new byte[] { 0x01, 0x00, 0x00, 0x00 }; int number = BitConverter.ToInt32(byteArray, 0); // 结果为 1 ``` `BitConverter.ToInt32` 方法可以从指定的索引位置读取四个字节,并将其转换为一个 `int` 值[^2]。 #### 3. 将 byte 数组转换为 `double`(双精度浮点数) ```csharp byte[] doubleBytes = new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF0, 0x3F }; double value = BitConverter.ToDouble(doubleBytes, 0); // 结果为 1.0 ``` `BitConverter.ToDouble` 方法可以从指定的索引位置读取八个字节,并将其转换为一个 `double` 值[^2]。 #### 4. 使用 `Convert` 类进行字符串中间转换 如果需要先将 byte 数组转换为字符串,然后再转换为数字,可以结合 `Encoding` 和 `Convert` 类完成: ```csharp byte[] byteArray = new byte[] { 0x31, 0x32 }; // 表示 ASCII 字符 "12" string str = System.Text.Encoding.ASCII.GetString(byteArray); // 转换为字符串 "12" int num = Convert.ToInt32(str); // 结果为 12 ``` 这里首先通过 `System.Text.Encoding.ASCII.GetString` 将 byte 数组转换为字符串,然后使用 `Convert.ToInt32` 将字符串转换为整数[^3]。 #### 5. 自定义逻辑实现转换 如果需要更灵活的转换逻辑,可以通过手动计算实现。例如,将 byte 数组视为小端序或大端序的整数: ```csharp byte[] byteArray = new byte[] { 0x01, 0x00, 0x00, 0x00 }; // 小端序表示整数 1 int number = (int)(byteArray[0] | byteArray[1] << 8 | byteArray[2] << 16 | byteArray[3] << 24); // 结果为 1 ``` 此方法适用于需要对字节顺序进行自定义处理的情况。 --- ### 注意事项 - 确保 byte 数组的长度与目标数据类型匹配,否则可能会抛出异常。 - 如果涉及浮点数转换,请注意字节顺序(小端序或大端序)的影响[^2]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值