【问题标题】:convert string to byte array [duplicate]将字符串转换为字节数组[重复]
【发布时间】:2011-07-31 18:28:43
【问题描述】:

可能重复:
How do you convert Byte Array to Hexadecimal String, and vice versa, in C#?

是否可以用完全相同的方式将字符串的内容转换为字节数组?

例如:我有一个字符串:

string strBytes="0xab, 0xcd, 0xef, 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0x01, 0x23, 0x45, 0x67, 0x89";

如果我将 strBytes 传递给它,是否有任何函数可以给我以下结果。

Byte[] convertedbytes ={0xab, 0xcd, 0xef, 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0x01, 0x23, 0x45, 0x67, 0x89};

【问题讨论】:

标签: c# .net


【解决方案1】:

没有内置方法,但您可以使用 LINQ 来做到这一点:

byte[] convertedBytes = strBytes.Split(new[] { ", " }, StringSplitOptions.None)
                                .Select(str => Convert.ToByte(str, 16))
                                .ToArray();

【讨论】:

  • 对逗号后的空格敏感
  • @sll,确实,尽管提问者代码中的格式看起来足够严格。但是,从您的答案中复制修复是不公平的,不是吗? ;)
【解决方案2】:
string strBytes="0xab, 0xcd, 0xef, 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0x01, 0x23, 0x45, 0x67, 0x89";

string[] toByteList = strBytes.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntires);

byte[] converted = new byte[toByteList.Length];

for (int index = 0; index < toByteList.Length; index++)
{
    converted[index] = Convert.ToByte(toByteList[index], 16);//16 means from base 16
}

【讨论】:

    【解决方案3】:
    string strBytes = "0xab, 0xcd, 0xef, 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0x01, 0x23, 0x45, 0x67, 0x89";
    
    IEnumerable<byte> bytes = strBytes.Split(new [] {','}).Select(x => Convert.ToByte(x.Trim(), 16));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-07-24
      • 1970-01-01
      • 1970-01-01
      • 2013-07-24
      • 2021-11-11
      • 2021-02-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多