On Jan 31, 2012, at 12:01 PM, Richard wrote:
In article <20120131162102.GB30381 at brevard.conman.org>,
Sean Conner <spc at conman.org> writes:
A friend recently raised an issue with some code
I wrote (a hex dump
routine) saying it depended upon ASCII and thus, would break on non-ASCII
based systems (and proposed a solution, but that's beside the issue here).
I assume he's saying this because you did something like '0' + x or
'A' + x to compute the hex digits. The obvious fix is to instead
index a string by the digit value:
"0123456789abcdef"[x]
Indeed, in most systems I can think of (at least ones that support
indirect addressing, which is most aside from the tiniest of 8-bits),
that'll produce faster code than the if/then construct required otherwise.
Indeed that was the case. I had:
while(size--)
{
dest[size] = (char)((value & 0x0F) + '0');
if (dest[size] > '9') dest[size] += 7;
value >>= 4;
}
And when I changed the code to:
while(size--)
{
dest[size] = "0123456789ABCDEF"[value & 0x0F];
value >>= 4;
}
It almost doubled the speed of the program (compiled with "gcc -O3
-fomit-frame-pointer -NDEBUG"), which really surprised me. I didn't think
modern systems were that about about handling branches.
-spc (But I'm still interested in my original question though ... )