将字节数组转换为int

我想在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 } 

谁能给我一些想法?

BitConverter是正确的方法。

您的问题是因为您在承诺时仅提供了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; } 

目前尚不清楚你的问题的第二部分(涉及字符串)应该产生什么,但我想你想要hex数字? BitConverter也可以提供帮助,如前面的问题所述 。

 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. 这是正确的,但你错过了, Convert.ToInt32 ‘想要’32位(32/8 = 4字节)的信息进行转换,所以你不能只转换一个字节:`new byte [] {0x32}

  2. 绝对是你遇到的同样的麻烦。 并且不要忘记您使用的编码:从编码到编码,您有“每个符号不同的字节数”

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

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

这样做的另一个好处是能够通过操纵偏移量将多个整数解析成数组。