Byte数组与其它类型间的转换

可以通过BitConverter类来将字节数组转换为其它类型

返回类型方法
boolToBoolean(Byte[], Int32)
charToChar(Byte[], Int32)
doubleToDouble(Byte[], Int32)
shortToInt16(Byte[], Int32)
intToInt32(Byte[], Int32)
longToInt64(Byte[], Int32)
floatToSingle(Byte[], Int32)
ushortToUInt16(Byte[], Int32)
uintToUInt32(Byte[], Int32)
ulong

ToUInt64(Byte[], Int32)

在运用BitConverter类时,要记住的一个重点是它的行为取决于硬件架构(代码在该硬件架构上运行)的字节顺序(endianness)——就是说,integer字节在内存中的存储顺序。如果你将bit保存为可以在许多不同平台上读取的一个文件格式,那么就会出问题。BitConverter有一个公有的IsLittleEndian字段。

例如在计算机结构为 little-endian 的情况下反转数组(即首先存储最低有效字节),然后调用 ToInt32(Byte[], Int32) 方法以将数组中的四个字节转换为 int。ToInt32(Byte[], Int32) 的第二个参数指定字节数组的起始索引。

byte[] bytes = { 0, 0, 0, 25 };

// If the system architecture is little-endian (that is, little end first),
// reverse the byte array.
if (BitConverter.IsLittleEndian)
    Array.Reverse(bytes);

int i = BitConverter.ToInt32(bytes, 0);
Console.WriteLine("int: {0}", i);
// Output: int: 25

在此示例中,调用 BitConverter 类的 GetBytes(Int32) 方法以将 int 转换为字节数组。

Bb384066.alert_note(zh-cn,VS.90).gif说明:

输出可能会根据计算机结构的 endian 设置而不同。

byte[] bytes = BitConverter.GetBytes(201805978);
Console.WriteLine("byte array: " + BitConverter.ToString(bytes));
// Output: byte array: 9A-50-07-0C

转载于:https://www.cnblogs.com/chengxing/articles/1729142.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值