繁体   English   中英

C#-转换int并将其放入带偏移量的字节数组的最快方法

[英]C# - Fastest way to convert an int and put it in a byte array with an offset

我正在编写自定义字节流,并且我最希望以最快的方式工作的写/读方法。 这是我目前对int32的write和read方法的实现:

    public void write(int value)
    {
        unchecked
        {
            bytes[index++] = (byte)(value);
            bytes[index++] = (byte)(value >> 8);
            bytes[index++] = (byte)(value >> 16);
            bytes[index++] = (byte)(value >> 24);
        }
    }

    public int readInt()
    {
        unchecked
        {
            return bytes[index++] |
                (bytes[index++] << 8) |
                (bytes[index++] << 16) |
                (bytes[index++] << 24);
        }
    }

但是我真正想要做的是将“ int ”转换为字节指针(或类似的指针),然后将内存复制到具有给定“ index ”作为offset的“ bytes ”数组中。 C#甚至可能吗?

目标是:
避免创建新的数组。
避免循环。
避免多次分配“ index ”变量。
减少指令数量。

您的代码非常快,但是您可以通过以下更改来提高速度(几乎快2倍):

bytes[index] = (byte)(value);
bytes[index+1] = (byte)(value >> 8);
bytes[index+2] = (byte)(value >> 16);
bytes[index+3] = (byte)(value >> 24);
index = index + 4;
unsafe
{
    fixed (byte* pbytes = &bytes[index])
    {
        *(int*)pbytes = value;
        value = *(int*)pbytes;
    }
}

但是要小心可能发生的数组索引溢出。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM