有谁知道是否有.NET 函数可以在字节数组中交换字节?
例如,假设我有一个具有以下值的字节数组:
byte[] arr = new byte[4];
[3] 192
[2] 168
[1] 1
[0] 4
Run Code Online (Sandbox Code Playgroud)
我想交换它们,使数组变为:
[3] 168
[2] 192
[1] 4
[0] 1
Run Code Online (Sandbox Code Playgroud)
[3] 的 val 与 [2] 的 val 和 [1] 的 val 与 [0] 的 val 交换
这个扩展方法怎么样:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
用法:
class Program
{
void ExampleUsage()
{
var buf = new byte[] {4, 1, 168, 192};
buf.SwapBytes(0, 1);
buf.SwapBytes(2, 3);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4051 次 |
| 最近记录: |