[英]How to convert the string with Byte to byte array in c#
I have a string with byte format in it as below我有一个字节格式的字符串,如下所示
var string="22-74-68-64-62-32-75-74-71-53-5A-6D-44-32-65-61-38-39-43-6A-39-4A-41-3D-3D-22"
Convert this to byte array as将其转换为字节数组为
byte[] arr=[22-74-68-64-62-32-75-74-71-53-5A-6D-44-32-65-61-38-39-43-6A-39-4A-41-3D-3D-22]
using System;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
string input = "22-74-68-64-62-32-75-74-71-53-5A-6D-44-32-65-61-38-39-43-6A-39-4A-41-3D-3D-22";
//Split string by '-'
string[] spl = input.Split('-');
//Parse bytes and add them to a list
List<byte> buf = new List<byte>();
foreach(string s in spl) {
buf.Add(byte.Parse(s, System.Globalization.NumberStyles.HexNumber));
}
//Convert list to byte[]
byte[] bytes = buf.ToArray();
//Print byte[] into console
foreach(byte b in bytes)
Console.WriteLine(b.ToString("X2"));
}
}
The above code will cause an exception if the input is not a perfect string of bytes delimited by dashes.如果输入不是由破折号分隔的完美字节字符串,则上述代码将导致异常。 If you're not expecting a perfect input you'll have to use byte.TryParse
like so:如果您不期待完美的输入,则必须像这样使用byte.TryParse
:
using System;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
string input = "22-74-68-64-62-32-75-74-71-53-5A-XX-wrgererh-6D-44-32-65-61-38-39-43-6A-39-4A-41-3D-3D-22";
//Split string by '-'
string[] spl = input.Split('-');
//Parse bytes and add them to a list
List<byte> buf = new List<byte>();
byte tb;
foreach(string s in spl) {
if(byte.TryParse(s, System.Globalization.NumberStyles.HexNumber, null, out tb))
buf.Add(tb);
}
//Convert list to byte[]
byte[] bytes = buf.ToArray();
//Print byte[] into console
foreach(byte b in bytes)
Console.WriteLine(b.ToString("X2"));
}
}
你可以使用Linq
把它弄得非常整洁
byte[] arr = input.Split('-').Select(i => byte.Parse(i, System.Globalization.NumberStyles.HexNumber)).ToArray();
Slightly more succinct with Convert.ToByte
使用Convert.ToByte
稍微简洁一点
var bytes = input.Split('-')
.Select(x => Convert.ToByte(x,16))
.ToArray();
Additional resources其他资源
ToByte(String, Int32) ToByte(字符串,Int32)
Converts the string representation of a number in a specified base to an equivalent 8-bit unsigned integer.将指定基数中数字的字符串表示形式转换为等效的 8 位无符号整数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.