Main Site Documentation

Snippet - HEX to long


#1

I just posted HEX to long on Codeshare. Feel free to discuss and make suggestions here.


#2

@ Luc Vdbr - Thanks for the code. If I could offer two improvements that will increase performance by about 35%

[ol]Remove the SubString and access the characters of the source string directly. This will avoid the creation of temporary strings on the managed heap and therefore reduce the number of GCs incurred.
Hoist the hex.Length call out of the loop. This is contrary to the desktop Framework which doing what you have done will actually improve performance, but the nature of .NETMF is that this advantage is totally negated by the lack of a JIT and actually incurs significant overhead[/ol]

The quick tests I did on the NETMF emulator gave about 18%-19% speed improvement by removing the substring and went up to 35% when hoisting the hex.Length call.


static long HexToLong2(string hex)
{
  int c;
  long r = 0;
  int length = hex.Length;
  for (int ix = 0; ix < length; ix++)
  {
    r <<= 4;
    c = (int)hex[ix] - 48;
    if (c > 9) c -= 7;
    r += c;
    }
    return r;
}