Improving method to read signed 8-bit integers from hexadecimal.

Posted by JYelton on Stack Overflow See other posts from Stack Overflow or by JYelton
Published on 2010-04-27T00:49:21Z Indexed on 2010/04/27 2:03 UTC
Read the original article Hit count: 379

Filed under:
|
|
|

Scenario:

I have a string of hexadecimal characters which encode 8-bit signed integers. Each two characters represent a byte which employ the leftmost (MSB) bit as the sign (rather than two's complement). I am converting these to signed ints within a loop and wondered if there's a better way to do it. There are too many conversions and I am sure there's a more efficient method that I am missing.

Current Code:

string strData = "FFC000407F"; // example input data, encodes: -127, -64, 0, 64, 127
int v;
for (int x = 0; x < strData.Length/2; x++)
{
    v = HexToInt(strData.Substring(x * 2, 2));
    Console.WriteLine(v); // do stuff with v
}

private int HexToInt(string _hexData)
{
    string strBinary = Convert.ToString(Convert.ToInt32(_hexData, 16), 2).PadLeft(_hexData.Length * 4, '0');
    int i = Convert.ToInt32(strBinary.Substring(1, 7), 2);
    i = (strBinary.Substring(0, 1) == "0" ? i : -i);
    return i;
}

Question:

Is there a more streamlined and direct approach to reading two hex characters and converting them to an int when they represent a signed int (-127 to 127) using the leftmost bit as the sign?

© Stack Overflow or respective owner

Related posts about c#

Related posts about signed