0

Possible Duplicate:
How to convert numbers between hexadecimal and decimal in C#?

I'm having struggle with converting to signed int using c# lets say I have the fallowing string:

AAFE B4FE B8FE

here we have 3 samples. each sample (signed 16 bits) is written as an ASCII hexadecimal sequence of 4 digits (2x2 digits/byte).

any suggestions? Thank you.

Community
  • 1
  • 1
AnasOta
  • 3
  • 3

2 Answers2

1

You can parse strings of numbers of any standard base using overloads in the Convert class that accept a base. In this case, you'd probably want this overload.

Then you could do something like this:

var groupings = "AAFE B4FE B8FE".Split();
var converted = groupings
    .Select(grouping => Convert.ToInt16(grouping, 16))
    .ToList();
Jeff Mercado
  • 129,526
  • 32
  • 251
  • 272
1

If you need to specify the endian-ness of the parsed values (instead of assuming that they are in little-endian byte order), then you need to place each byte in the appropriate place within the resulting short.

Note that exceptions will be thrown in HexToByte if the string values are not well formatted.

static byte HexToByte(string value, int offset)
{
   string hex = value.Substring(offset, 2);
   return byte.Parse(hex, NumberStyles.HexNumber);
}

static short HexToSigned16(string value, bool isLittleEndian)
{
   byte first = HexToByte(value, 0);
   byte second = HexToByte(value, 2);

   if (isLittleEndian) 
       return (short)(first | (second << 8));
   else
       return (short)(second | (first << 8));
}

...

string[] values = "AAFE B4FE B8FE".Split();
foreach (string value in values)
{
   Console.WriteLine("{0} == {1}", value, HexToSigned16(value, true));
}
Monroe Thomas
  • 4,962
  • 1
  • 17
  • 21