c#分割一个带长度的字节数组的字符串
时间: 2024-03-21 07:40:40 浏览: 29
如果你有一个带长度的字节数组,想要将其转换为字符串并分割字符串,可以使用以下方法:
```csharp
byte[] bytes = new byte[] { 0x05, 0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x06, 0x57, 0x6f, 0x72, 0x6c, 0x64 };
string str = Encoding.ASCII.GetString(bytes); // 将字节数组转换为字符串
int index = 0;
string[] splitStrings = new string[2];
for (int i = 0; i < splitStrings.Length; i++)
{
int length = bytes[index]; // 获取当前字符串的长度
index++; // 索引加1,跳过长度字节
splitStrings[i] = Encoding.ASCII.GetString(bytes, index, length); // 获取当前字符串
index += length; // 索引加上当前字符串的长度,跳过当前字符串的字节
}
```
上面的代码首先将字节数组转换为字符串,然后使用一个索引变量 `index` 来遍历字节数组。在每次循环中,我们读取当前字符串的长度,然后使用 `Encoding.ASCII.GetString` 方法获取当前字符串的字节并转换为字符串。最后,我们将索引加上当前字符串的长度以跳过当前字符串的字节。
相关问题
C# 16进制字符串转字节数组
可以使用 `System.Linq` 命名空间下的 `Enumerable.Range` 方法和 `Convert.ToByte` 方法来实现:
```csharp
string hexString = "FFAABBCC";
byte[] bytes = Enumerable.Range(0, hexString.Length)
.Where(x => x % 2 == 0)
.Select(x => Convert.ToByte(hexString.Substring(x, 2), 16))
.ToArray();
```
上面的代码中,我们首先定义了一个 16 进制字符串 `hexString`,然后使用 `Enumerable.Range` 方法生成一个从 0 到字符串长度的数字序列,通过 `Where` 方法筛选出偶数位置的字符(因为每两个字符表示一个字节),再使用 `Select` 方法将每两个字符转换为一个字节,并使用 `ToArray` 方法转换为字节数组。
C# 字节数组转字符串
在 C# 中将字节数组转换为字符串,可以使用 Encoding 类的 GetString() 方法。以下是示例代码:
```csharp
byte[] byteArray = { 72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100 }; // 字节数组
string str = Encoding.UTF8.GetString(byteArray); // 转换为字符串
Console.WriteLine(str); // 输出: Hello World
```
在上面的示例中,我们使用 UTF8 编码将字节数组转换为字符串,你也可以根据具体需求选择其他编码方式。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)