Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations wOOdy-Soft on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Hex to int in a better way?

Status
Not open for further replies.

stuartd

Programmer
Jan 8, 2001
146
US
Hi,

I am converting a hex pair to a single char.

Can this be done in a tidier way? - there seems to be a lot of casting and i am having to use a temp int to store the halfway results. I am sure this can be done in fewer lines (and casts) in 'c'.

Here is my code:

private char HexPair2Char(string strHexPair)
{
// Locals
int i_temp, i_charvalue;
char c_char;

// Initiallise var for compiler . . .
i_charvalue=0;
for(int x=0;x<=1;x++)
{
// Get the value . . .
c_char=Convert.ToChar( strHexPair.Substring(1,1));
if(c_char>(int)'9')
{
i_temp=(int)c_char-(int)'A'+10;
}
else
{
i_temp=(int)c_char-(int)'0';
}

// Convert to int value . . .
if(x==0)
{
i_charvalue=i_temp*16;
}
else
{
i_charvalue=i_charvalue + i_temp;
}
}

return((char)i_charvalue);
}



SD
 
I'd sugget using the version of ToInt32 that uses a base.

Code:
iInt = Convert.ToInt32(sHexString, 16)

-Sean

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top