0

I'm trying to convert a string representing a hexadecimal value, for example "A0F3", into a hexadecimal or byte value. 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.

I apprecciate your help.

CodeXtack
  • 111
  • 1
  • 3
  • 11
  • `int.Parse(value, System.Globalization.NumberStyles.AllowHexSpecifier);` – Gusman Feb 01 '18 at 18:44
  • Possible duplicate of [How can I convert a hex string to a byte array?](https://stackoverflow.com/questions/321370/how-can-i-convert-a-hex-string-to-a-byte-array) – maccettura Feb 01 '18 at 18:44

1 Answers1

1

Convert.ToInt32 has an overload that takes the base as a parameter.

Convert.ToInt32("A0F3",16) should yield the desired result.

However, if you want to code it yourself as an exercise, the general algorithm is: Each character corresponds to a 4 bit value. 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:

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;
}
driis
  • 161,458
  • 45
  • 265
  • 341