C# byte[]反转
时间: 2023-08-29 07:08:16 浏览: 57
将一个byte数组进行反转,可以使用以下代码实现:
```csharp
// 将一个byte数组进行反转
public byte[] ReverseBytes(byte[] bytes)
{
int length = bytes.Length;
byte[] result = new byte[length];
for (int i = 0; i < length; i++)
{
result[length - i - 1] = bytes[i];
}
return result;
}
```
示例:
```csharp
byte[] bytes = new byte[] { 0x01, 0x02, 0x03, 0x04 };
byte[] reversedBytes = ReverseBytes(bytes); // 反转后的byte数组为 { 0x04, 0x03, 0x02, 0x01 }
```
注意:这里的代码返回了一个新的数组,原数组并没有被修改。如果需要在函数内部修改原数组的值,可以使用`ref`关键字。
相关问题
C# int转16进制byte
可以使用以下代码将C#中的int类型转换为16进制byte类型:
```csharp
int intValue = 255;
byte[] hexValue = BitConverter.GetBytes(intValue);
Array.Reverse(hexValue); // reverse the byte order if necessary
string hexString = BitConverter.ToString(hexValue).Replace("-", "");
```
在上面的代码中,我们首先将int类型的值存储在intValue变量中。然后,我们使用BitConverter.GetBytes方法将intValue转换为byte数组。由于这个方法返回的是一个小端字节序的数组,我们使用Array.Reverse方法将其反转以获取正确的字节顺序。最后,我们使用BitConverter.ToString方法将byte数组转换为16进制字符串,并使用Replace方法删除其中的横线字符。
c#将ushort转换为16进制byte
在 C# 中,可以使用 BitConverter.GetBytes 方法将 ushort 类型转换为 byte 数组,然后再将 byte 数组转换为 16 进制字符串。具体代码如下:
```csharp
ushort num = 12345;
byte[] bytes = BitConverter.GetBytes(num); // 将 ushort 转换为 byte 数组
string hex = BitConverter.ToString(bytes).Replace("-", ""); // 将 byte 数组转换为 16 进制字符串
```
其中,`BitConverter.GetBytes` 方法将 ushort 类型转换为 byte 数组,`BitConverter.ToString` 方法将 byte 数组转换为 16 进制字符串,`Replace` 方法用于去除字符串中的分隔符 `-`。
如果想要将 ushort 直接转换为 16 进制 byte 数组,可以使用 BitConverter.GetBytes 方法配合 LINQ 的 Select 方法,如下所示:
```csharp
ushort num = 12345;
byte[] bytes = BitConverter.GetBytes(num).Reverse().ToArray(); // 将 ushort 转换为 16 进制 byte 数组
string hex = BitConverter.ToString(bytes).Replace("-", ""); // 将 byte 数组转换为 16 进制字符串
```
其中,`Reverse` 方法用于反转 byte 数组的顺序,因为 BitConverter.GetBytes 方法返回的 byte 数组顺序与我们期望的顺序是相反的。