简体   繁体   English

如何将十六进制值的文本表示形式转换为十六进制值?

[英]How can I convert a textual representation of a hexadecimal value to a hexadecimal value?

I'm trying to convert a string representing a hexadecimal value, for example "A0F3" , into a hexadecimal or byte value. 我正在尝试将表示十六进制值(例如"A0F3"的字符串转换为十六进制或byte值。 I tryed to do something like this: 我试图做这样的事情:

string text = "A0F3";
char[] chars = text.ToCharArray();
StringBuilder stringBuilder =  new StringBuilder();

foreach(char c in chars)
{
  stringBuilder.Append(((Int16)c).ToString("x"));
}

String textAsHex = stringBuilder.ToString();
Console.WriteLine(textAsHex);

But obviously I'm not converting the final value to a byte value, I'm stuck. 但是很明显,我没有将最终值转换为byte值,而是被卡住了。

I apprecciate your help. 感谢您的帮助。

Convert.ToInt32 has an overload that takes the base as a parameter. Convert.ToInt32具有一个以基数为参数的重载。

Convert.ToInt32("A0F3",16) should yield the desired result. Convert.ToInt32("A0F3",16)应该会产生所需的结果。

However, if you want to code it yourself as an exercise, the general algorithm is: Each character corresponds to a 4 bit value. 但是,如果要自己作为练习进行编码,则一般算法为:每个字符对应一个4位值。 Convert each character to it's value and create an integer by shifting bits left as you go. 将每个字符转换为其值,并通过向左移动位来创建整数。 This could be a general algorithm, please don't use without adding bounds checking, 0x prefix support, etc (And you really should be using the framework built-ins for production code) - but here goes: 这可能是一个通用算法,请不要在未添加边界检查, 0x前缀支持等的情况下使用(而且您确实应该使用内置的框架来生成代码)-但这里有:

public static int FromHexString(string hex)
{
       int value = 0;
       foreach (char c in hex.ToUpperInvariant().Trim())
       {
           var n = c >= '0' && c <= '9' ? c - '0' : c - 'A' + 10;
           value = (value << 4) | n;
       }

       return value;
}

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

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