Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/337.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 字符串到字节[],不编码或更改字符串处的实际字节_C#_String_Type Conversion_Bytearray - Fatal编程技术网

C# 字符串到字节[],不编码或更改字符串处的实际字节

C# 字符串到字节[],不编码或更改字符串处的实际字节,c#,string,type-conversion,bytearray,C#,String,Type Conversion,Bytearray,假设我得到了以下字节[] 0C 00 21 08 01 00 00 00 86 1B 06 00 54 51 53 65 72 76 65 72 使用bitconverter bitconverter.ToString我可以将其转换为 0C-00-21-08-01-00-00-00-86-1B-06-00-54-51-53-65-72-76-65-72 如何将其从字符串转换回字节[]以获取 0C 00 21 08 01 00 00 00 86 1B 06 00 54 51 53 65 72

假设我得到了以下
字节[]

0C 00 21 08 01 00 00 00 86 1B 06 00 54 51 53 65 72 76 65 72
使用
bitconverter bitconverter.ToString
我可以将其转换为

0C-00-21-08-01-00-00-00-86-1B-06-00-54-51-53-65-72-76-65-72
如何将其从字符串转换回
字节[]
以获取

0C 00 21 08 01 00 00 00 86 1B 06 00 54 51 53 65 72 76 65 72
ascii编码和其他方法总是让我得到字符串的等效字节,但我真正需要的是字符串必须是byte[],因为它是这样的,我知道如果我做了一个反向操作(使用getbytes然后使用tostring),我会得到相同的字符串,但我关心的是在getbytes时获得确切的字节

正如我所说

放置

0C-00-21-08-01-00-00-00-86-1B-06-00-54-51-53-65-72-76-65-72
作为
字符串

得到

0C 00 21 08 01 00 00 00 86 1B 06 00 54 51 53 65 72 76 65 72
作为
字节[]

0C 00 21 08 01 00 00 00 86 1B 06 00 54 51 53 65 72 76 65 72

提前感谢

您可以在
System.Runtime.Remoting.Metadata.W3cXsd2001
命名空间中使用
SoapHexBinary

string s = "0C-00-21-08-01-00-00-00-86-1B-06-00-54-51-53-65-72-76-65-72";
byte[] buf  = SoapHexBinary.Parse(s.Replace("-"," ")).Value;
你需要这个

byte[] bytes = str.Split('-').Select(s => Convert.ToByte(s, 16)).ToArray();

请记住,BitConverter.ToString返回等效的十六进制字符串表示形式,因此 如果您决定继续使用,请按以下步骤进行转换:

string temp = BitConverter.ToString(buf);//buf is your array.
byte[] newbuf = temp.Split('-').Select(s => Convert.ToByte(s,16)).ToArray();
但将字节转换为字符串并返回的最安全方法是base64:

string str = Convert.ToBase64String(buf);
byte[] result = Convert.FromBase64String(str);

可能是重复的。谢谢你,伙计,不奇怪为什么我自己没有弄明白:)这是关于
不获取“无效”unicode序列(例如encoding.GetString(byteArray))
。如果只使用字符
0-9
A-F
,会出现什么问题?