如何读取byte []中的整数

时间:2011-06-16 10:01:34

标签: c# .net

我有一个字节数组,我想从这个数组中读取一个整数。我该怎么办?

这样的事情:

 int i;

 tab = new byte[32];

 i = readint(tab,0,3); // i = int from tab[0] to tab[3] (int = 4 bytes?)

 i = readint(tab,4,7);

等...

4 个答案:

答案 0 :(得分:14)

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

参考:How to: Convert a byte Array to an int

答案 1 :(得分:5)

此外,Jon Skeet的miscutil library中有一个名为Endian的类,它实现了字节数组和各种基本类型之间的转换方法,并考虑了字节序。

对于您的问题,使用方法如下:

// Input data
byte[] tab = new byte[32];

// Pick the appropriate endianness
Endian endian = Endian.Little;

// Use the appropriate endian to convert
int a = endian.ToInt32(tab, 0);
int b = endian.ToInt32(tab, 4);
int c = endian.ToInt32(tab, 8);
int d = endian.ToInt32(tab, 16);
...

Endian类的简化版本如下:

public abstract class Endian
{
    public short ToInt16(byte[] value, int startIndex)
    {
        return unchecked((short)FromBytes(value, startIndex, 2));
    }

    public int ToInt32(byte[] value, int startIndex)
    {
        return unchecked((int)FromBytes(value, startIndex, 4));
    }

    public long ToInt64(byte[] value, int startIndex)
    {
        return FromBytes(value, startIndex, 8);
    }

    // This same method can be used by int16, int32 and int64.
    protected virtual long FromBytes(byte[] buffer, int startIndex, int len);
}

然后FromBytes抽象方法对每种端序类型实现不同。

public class BigEndian : Endian
{
    protected override long FromBytes(byte[] buffer, int startIndex, int len)
    {
        long ret = 0;
        for (int i=0; i < len; i++)
        {
            ret = unchecked((ret << 8) | buffer[startIndex+i]);
        }
        return ret;
    }
}

public class LittleEndian : Endian
{
    protected override long FromBytes(byte[] buffer, int startIndex, int len)
    {
        long ret = 0;
        for (int i=0; i < len; i++)
        {
            ret = unchecked((ret << 8) | buffer[startIndex+len-1-i]);
        }
        return ret;
    }
}

答案 2 :(得分:3)

您可以使用BitConverter.ToInt32。看看this

答案 3 :(得分:2)

如果你想手动完成,那就应该这样做了!

byte[] data = ...;
int startIndex = 0;
int value = data[startIndex];

for (int i=1;i<4;i++)
{
  value <<= 8;
  value |= data[i+startIndex];
}