简体   繁体   English

如何将包含十六进制对的字符串转换为字节?

[英]How do I convert a string containing a hexadecimal pair to a byte?

I have a string containing a hexadecimal value. 我有一个包含十六进制值的字符串。 Now I need the content of this string containing the hexadecimal as a byte variable. 现在我需要包含十六进制的字符串的内容作为字节变量。 How should I do this without changing the hexadecimal value? 如何在不更改十六进制值的情况下执行此操作?

An alternative to the options posted so far: 到目前为止发布的选项的替代方案:

byte b = Convert.ToByte(text, 16);

Note that this will return 0 if text is null; 请注意,如果text为null,则返回0; that may or may not be the result you want. 这可能是您想要的结果,也可能不是。

String strHex = "ABCDEF";
Int32 nHex = Int32.Parse(strHex, NumberStyles.HexNumber);
Byte[] bHex = BitConverter.GetBytes(nHex);

I think that's what you're looking for. 我认为这就是你要找的东西。 If not, post an update with a more explicit definition of what you're looking for. 如果没有,请发布更新,更明确地定义您要查找的内容。

If it is just a single byte in the string, you can do this: 如果它只是字符串中的单个字节,则可以执行以下操作:

        string s = "FF";
        byte b;


        if (byte.TryParse(s, NumberStyles.HexNumber, null, out b))
        {
            MessageBox.Show(b.ToString());  //255
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM