简体   繁体   English

在字节数组中交换字节

[英]Swap bytes within an byte array

Does anyone know if there's a .NET function to swap bytes within an Byte Array? 有谁知道是否存在.NET函数来交换字节数组中的字节?

For example, lets say I have a byte array with the following values: 例如,假设我有一个带有以下值的字节数组:

byte[] arr = new byte[4];

[3] 192
[2] 168
[1] 1
[0] 4

I want to swap them so that the array becomes: 我想交换它们,以便数组变为:

[3] 168
[2] 192
[1] 4
[0] 1

Val of [3] was swapped with val of [2] and val of [1] with val of [0] [3]的值交换为[2]的值,[1]的值交换为[0]的值

How about this extension method: 这个扩展方法如何:

public static class ExtensionMethods
{
    /// <summary>Swaps two bytes in a byte array</summary>
    /// <param name="buf">The array in which elements are to be swapped</param>
    /// <param name="i">The index of the first element to be swapped</param>
    /// <param name="j">The index of the second element to be swapped</param>
    public static void SwapBytes(this byte[] buf, int i, int j)
    {
        byte temp = buf[i];
        buf[i] = buf[j];
        buf[j] = temp;
    }
}

Usage: 用法:

class Program
{
    void ExampleUsage()
    {
        var buf = new byte[] {4, 1, 168, 192};
        buf.SwapBytes(0, 1);
        buf.SwapBytes(2, 3);
    }
}

I sounds like you want to swap byte pairs in-place across the entire array. 听起来您想在整个数组中就地交换字节对。 You could do something like this, process the array from left to right: 您可以执行以下操作,从左到右处理数组:

public static void SwapPairsL2R( this byte[] a )
{
  for ( int i = 0 ; i < a.Length ; i+=2 )
  {
    int t  = a[i]   ;
    a[i]   = a[i+1] ;
    a[i+1] = a[i]   ;
    a[i]   = t      ;
   }
   return ;
}

Swapping right-left wouldn't be much different. 左右交换不会有太大不同。

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

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