【问题标题】:string to byte[] without encoding or changing actual bytes at stringstring 到 byte[] 而不编码或更改字符串中的实际字节
【发布时间】:2013-07-27 20:07:53
【问题描述】:

假设我得到了以下byte[]

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

如何将其从字符串转换回byte[] 以获取

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

作为string

得到

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

作为byte[]

提前致谢

【问题讨论】:

标签: c# string type-conversion bytearray


【解决方案1】:

您可以在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;

【讨论】:

    【解决方案2】:

    你需要这个

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

    【讨论】:

    • 这行得通,谢谢哥们,不知道为什么我没有自己弄清楚:)
    【解决方案3】:

    请记住 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);
    

    【讨论】:

    猜你喜欢
    • 2014-04-15
    • 2018-06-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-13
    相关资源
    最近更新 更多