将字节数组转换为整数

11

我正在尝试在C#中进行一些转换,但是我不确定如何做到这一点:

private int byteArray2Int(byte[] bytes)
{
    // bytes = new byte[] {0x01, 0x03, 0x04};

    // how to convert this byte array to an int?

    return BitConverter.ToInt32(bytes, 0); // is this correct? 
    // because if I have a bytes = new byte [] {0x32} => I got an exception
}

private string byteArray2String(byte[] bytes)
{
   return System.Text.ASCIIEncoding.ASCII.GetString(bytes);

   // but then I got a problem that if a byte is 0x00, it show 0x20
}

有人能给我一些想法吗?


如果你喜欢走极端,你可以使用强制类型转换。 - Matt Parkins
4个回答

28

BitConverter是正确的方法。

你的问题是因为你承诺提供32位,但实际只提供了8位。尝试在数组中提供一个有效的32位数字,例如new byte[] { 0x32, 0, 0, 0 }

如果你想将任意长度的数组转换,你可以自己实现:

ulong ConvertLittleEndian(byte[] array)
{
    int pos = 0;
    ulong result = 0;
    foreach (byte by in array) {
        result |= ((ulong)by) << pos;
        pos += 8;
    }
    return result;
}
不清楚你提到的第二部分问题(涉及字符串)想要产生什么,但我猜想你想要十六进制数字?BitConverter也可以帮助实现这一点,正如早期问题所述。

一个字节列表就可以了,我认为我已经声明过了。 - olidev
1
在字节转换中使用foreach看起来真的很疯狂。 - Mikant
1
通常我们使用这种类型的转换来提高速度...不必担心我们工作的环境。foreach语法糖可能会使work变慢数百倍...我只想说,使用foreach关键字必须要有意识地认识到。 - Mikant
@Mikant: 我认为你把这个和其他情况搞混了。在数组上使用 foreach 是非常快的。如果这里有一个通用的接口,比如 IEnumerable<byte>,那么可能会出现性能问题。但我展示的代码没有“数百倍”的开销。你可能可以通过展开循环来挤出更多的性能,但那就是全部了。 - Ben Voigt
你建议的这个函数会产生警告:warning CS0675:位或运算符用于符号扩展操作数;请先考虑将其转换为较小的无符号类型。为什么? - user5387678
显示剩余2条评论

3
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);

1

一种快速简单的方法是使用Buffer.BlockCopy将字节复制到整数中:

UInt32[] pos = new UInt32[1];
byte[] stack = ...
Buffer.BlockCopy(stack, 0, pos, 0, 4);

这样做的另一个好处是可以通过操作偏移量将多个整数解析为数组。

1
  1. 这是正确的,但你遗漏了一个事实,Convert.ToInt32需要32位(32/8 = 4字节)的信息来进行转换,所以你不能只转换一个字节:`new byte [] {0x32}

  2. 你遇到了完全相同的问题。不要忘记你使用的编码方式:从一种编码到另一种编码,每个符号的字节数都不同。


  1. 没问题。
  2. 对于我来说,问题2不太清楚,所以我应该使用哪种编码格式?提前致谢。
- olidev

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接