2

我有一个来自测试设备的传入字节数组。字节数组可以是两个或四个字节长。我编写了以下代码将这些字节数组转换为无符号长整数:

private ulong GetUlongFrom2Bytes(byte MSB, byte LSB)
{
    return (ulong)((MSB << 8) + (LSB));
}

private ulong GetUlongFrom4Bytes(byte MSB, byte msb, byte lsb, byte LSB)
{
    return (ulong)((MSB << 24) + (msb << 16) + (lsb << 8) + (LSB));
}

相反,为了相反的方向,我执行以下代码:

private byte[] Get4Bytes(ulong parm1)
{
    byte[] retVal = new byte[4];

    retVal[0] = (byte)((parm1 >> 24) & 0xFF);
    retVal[1] = (byte)((parm1 >> 16) & 0xFF);
    retVal[2] = (byte)((parm1 >> 8) & 0xFF);
    retVal[3] = (byte)(parm1 & 0xFF);

    return retVal;
}

private byte[] Get8Bytes(ulong parm1, ulong parm2)
{
    byte[] retVal = new byte[8];

    Array.Copy(Get4Bytes(parm1), 0, retVal, 0, 4);
    Array.Copy(Get4Bytes(parm2), 0, retVal, 4, 4);

    return retVal;
}

我正在尝试调试我的代码以控制这台设备,我只是希望你们在这里对 SO 进行一次健全性检查,以确认此代码对于我正在尝试做的事情是正确编写的。

4

2 回答 2

4

假设您想要大端编码,那么是的:没问题。您可以使用BitConverter,但我认为您不这样做是对的 - 它涉及额外的数组分配,并强制您使用系统的字节序(通常是小字节序)。

通常,为了简单和高效,我会推荐此类代码与缓冲区/偏移 API 一起使用 - 即

private void Write32(ulong value, byte[] buffer, int offset)
{
    buffer[offset++] = (byte)((value >> 24) & 0xFF);
    buffer[offset++] = (byte)((value >> 16) & 0xFF);
    buffer[offset++] = (byte)((value >> 8) & 0xFF);
    buffer[offset] = (byte)(value & 0xFF);
}
于 2013-05-08T10:06:09.577 回答
1

这会做到:

static ulong SliceValue(byte[] bytes, int start, int length)
{
    var bytes = bytes.Skip(start).Take(length);

    ulong acc = 0;
    foreach (var b in bytes) acc = (acc * 0x100) + b;

    return acc;
}
于 2013-05-08T10:18:59.670 回答