You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
|
|
|
|
|
using System;
|
|
|
|
|
|
using System.Collections.Generic;
|
|
|
|
|
|
using System.Linq;
|
|
|
|
|
|
using System.Text;
|
|
|
|
|
|
using System.Threading.Tasks;
|
|
|
|
|
|
|
|
|
|
|
|
namespace Sln.Iot.Business
|
|
|
|
|
|
{
|
|
|
|
|
|
public class ToolBusiness
|
|
|
|
|
|
{
|
|
|
|
|
|
/// <summary>
|
|
|
|
|
|
/// 将偶数长度的byte数组中每对相邻元素(偶数下标和奇数下标)互换位置
|
|
|
|
|
|
/// </summary>
|
|
|
|
|
|
/// <param name="inputBytes">输入的byte数组(必须非空且长度为偶数)</param>
|
|
|
|
|
|
/// <returns>处理后的新byte数组</returns>
|
|
|
|
|
|
/// <exception cref="ArgumentNullException">输入数组为空时抛出</exception>
|
|
|
|
|
|
/// <exception cref="ArgumentException">输入数组长度为奇数时抛出</exception>
|
|
|
|
|
|
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;
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|