如何提高将byte []转换为int的性能?

时间:2011-01-28 20:44:58

标签: c# .net bytearray

我正在编写一个二进制文件转换器,我需要将1-6字节数组转换为int(短 - 长)值。目前我正在使用以下三个功能,我想知道是否还有提高性能?

private string byteToShortParse(byte[] recordData, int offset, int length)
{
    byte[] workingSet = new byte[2];
    Buffer.BlockCopy(recordData, offset, workingSet, 0, length);
    return (BitConverter.ToInt16(workingSet, 0).ToString());
}

private string byteToIntParse(byte[] recordData, int offset, int length)
{
    byte[] workingSet = new byte[4];
    Buffer.BlockCopy(recordData, offset, workingSet, 0, length);
    return (BitConverter.ToInt32(workingSet, 0).ToString());
}

private string byteToLongParse(byte[] recordData, int offset, int length)
{
    byte[] workingSet = new byte[8];
    Buffer.BlockCopy(recordData, offset, workingSet, 0, length);
    return (BitConverter.ToInt32(workingSet, 0).ToString());
}

2 个答案:

答案 0 :(得分:1)

<强> EDIT2:

我想如果你需要转换为int的字节数是可变长度(这看起来很奇怪),我建议这样做:

private string bytesToIntParse(byte[] recordData, int offset, int length)
{
    long result = 0;
    for (int i = 0; i < length; ++i)
    {
        result |= ((long)recordData[i + offset]) << (i * 8);
    }
    return result.ToString();
}

现在你有一个函数,没有Buffer.BlockCopy,它支持任何长度。

<强> EDIT1:

您可以使用不安全的代码,例如:

// I don't think you need to specify a length parameter, since int32 is always 4 bytes
private string byteToIntParse(byte[] recordData, int offset, int length)
{
    unsafe
    {
        fixed (byte* p = &recordData[offset])
        {
            // This result will differ on little and big endian architectures.
            return (*(int*)p).ToString();
        }
    }
}

但这就是BitConverter内部所做的,所以我认为你不会获得任何性能

为什么要将字节复制到workingSet?你可以:

return BitConverter.ToInt32(recordData, offset).ToString()

我猜这会带来性能提升,因为您不必每次都调用Buffer.BlockCopy:P

答案 1 :(得分:1)

是的,最佳变体是

private string byteToShortParse(byte[] recordData, int offset, int length)
    {
        if (length == 2)
        { 
             short i = (recordData[offset + 1] << 8) | recordData[offset];
             return i.ToString;
        } else return "";

    }

这同样适用于4字节和8字节值(只需要更多的移位)。