c# - 使此 C# SwapBytes 代码与 x64 兼容

标签 c# memory 64-bit

这是从“Endogine”引擎借来的一段代码。它应该交换任何字节数组的字节顺序:

unsafe protected void SwapBytes(byte* ptr, int nLength)
{
    for(long i = 0; i < nLength / 2; ++i) {
        byte t = *(ptr + i);
        *(ptr + i) = *(ptr + nLength - i - 1);
        *(ptr + nLength - i - 1) = t;
    }
}

当我以 x64 架构为目标时它似乎失败了,但我不明白为什么,因为没有指针被转换为 int32。 有什么帮助吗?

最佳答案

它似乎以什么方式失败了?看起来很简单。我会使用两个指针来让它更快:

unsafe protected void SwapBytes(byte* ptr, int nLength) {
  byte* ptr2 = ptr + nLength - 1;
  for(int i = 0; i < nLength / 2; i++) {
    byte t = *ptr;
    *ptr = *ptr2;
    *ptr2 = t;
    ptr++;
    ptr2--;
  }
}

但是,编译器非常擅长优化循环和数组访问。执行相同操作的托管代码很可能与不安全代码非常接近:

protected void SwapBytes(byte[] data) {
  for(int i = 0, j = data.Length - 1; i < data.Length / 2; i++, j--) {
    byte t = data[i];
    data[i] = data[j];
    data[j] = t;
  }
}

关于c# - 使此 C# SwapBytes 代码与 x64 兼容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2989237/

相关文章:

c# - 使用 linq 从键中获取值

c# - 使用反射测试方法是否具有特定签名

c# - 创建 Excel 工作表时出现 NullReferenceException

python - 计算 numpy memmap Infinity 输出的均值和方差

c++ - 在 incredibuild 中启用 Microsoft Visual Studio x64 工具

asp.net - 如何在 x64 中使用 WebDev.WebServer.exe (VS Web Server)?

c# - CScript 在 c# 中作为进程调用时仅打开 32 位版本

c# - Mailkit 身份验证失败

memory - 是否可以在 valgrind 中列出泄漏内存的位置?

c - 使用驱动程序从特定位置读取 RAM 数据?