C#从字节数组中获取第1个2个整数

时间:2019-02-20 17:56:27

标签: c# arrays bitconverter

我有一个字节[]这样

byte[] buffer = new byte[1024];

此字节[]可能具有以下值:

buffer = {0, 0, 0, 106, 0, 0, 0, 11, 64, 33, 50, 32, 32, 32, ....}

我正在尝试获取前8个字节,即:

0,0,0,106

0,0,0,11

,并将它们转换为106和11的整数。

我可以放心地假设前8个字节始终代表2个整数,如上面的示例,它们分别是106和11,并且它们采用4个字节的形式,其中1st 3为0,就像上面的例子。

两者都是4个有符号整数(按高低顺序排列)

我该如何在C#中做到这一点?

5 个答案:

答案 0 :(得分:3)

您所需要做的就是访问索引3和7:

int first = buffer[3];
int second = buffer[7];

byteint的隐式转换。

由于以下原因,这是可能的:

  

我可以放心地假设[...]它们采用4个字节的形式,其中第一个3为0

因此,您只需要每个4字节整数的最后一个字节即可。

答案 1 :(得分:3)

简单的DIY功能:

int BytesToInt32(byte[] buff, int offset)
{
    return (buff[offset + 0] << 24)
         + (buff[offset + 1] << 16)
         + (buff[offset + 2] << 8)
         + (buff[offset + 3]);
}

然后:

buffer = {0, 0, 0, 106, 0, 0, 0, 11, 64, 33, 50, 32, 32, 32, ....};
int a = BytesToInt32(buffer, 0);
int b = BytesToInt32(buffer, 4);

答案 2 :(得分:2)

我会将您的byte[]转换为MemoryStream(或将其保留为Stream)。然后根据需要使用BinaryReader。如果字节序不正确:C# - Binary reader in Big Endian?

答案 3 :(得分:1)

private static int BytesToInt(byte[] array, int startIndex){
    int toReturn = 0;
    for (int i = startIndex; i < startIndex + 4; i++)
    {
        toReturn = toReturn << 8;
        toReturn = toReturn + array[i];
    }
    return toReturn;
}

答案 4 :(得分:0)

使用convert类。

int myint1 = Convert.ToInt32(buffer[someIndex1]);
int myint2 = Convert.ToInt32(buffer[someIndex2]);

如其他人所述,如果可以保证索引4和索引7具有非零字节,则可以直接将其插入。