using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Sln.Iot.Business { public class ToolBusiness { /// /// 将偶数长度的byte数组中每对相邻元素(偶数下标和奇数下标)互换位置 /// /// 输入的byte数组(必须非空且长度为偶数) /// 处理后的新byte数组 /// 输入数组为空时抛出 /// 输入数组长度为奇数时抛出 public static byte[] SwapAdjacentBytes(byte[] inputBytes) { // 校验输入:数组不能为空 if (inputBytes == null) { throw new ArgumentNullException(nameof(inputBytes), "输入的byte数组不能为null"); } // 校验输入:数组长度必须为偶数 if (inputBytes.Length % 2 != 0) { throw new ArgumentException("输入的byte数组长度必须为偶数", nameof(inputBytes)); } // 创建原数组的副本,避免修改原数组 byte[] resultBytes = (byte[])inputBytes.Clone(); // 遍历数组,步长为2,交换每对相邻元素 for (int i = 0; i < resultBytes.Length; i += 2) { // 交换偶数下标(i)和奇数下标(i+1)的元素 byte temp = resultBytes[i]; resultBytes[i] = resultBytes[i + 1]; resultBytes[i + 1] = temp; } return resultBytes; } } }