Re: Hex to NSString or NSData
Re: Hex to NSString or NSData
- Subject: Re: Hex to NSString or NSData
- From: Clark Cox <email@hidden>
- Date: Sat, 9 May 2009 18:05:47 -0700
On Sat, May 9, 2009 at 4:05 PM, Gwynne Raskind <email@hidden> wrote:
> On May 9, 2009, at 5:20 PM, Marcel Weiher wrote:
>>>
>>> int hexDigitToInt(char d)
>>> {
>>> Â int result;
>>> Â switch (d) {
>>> Â Â Â case '0': result = 0; break;
>>> Â Â Â case '1': result = 1; break;
>>> [snip]
>>> Â Â Â case 'E': result = 14; break;
>>> Â Â Â case 'F': result = 15; break;
>>>
>>> Â Â Â default:
>>> Â Â Â Â Â result = 0xFF;
>>> Â }
>>>
>>> Â return result;
>>> }
>>> Although it might look ugly, this is one of the fasted methods using
>>> standard C that converts a hex digit (nibble) to an int (2 machine
>>> instructions).
>>
>> OK, how do you get it to compile to just two instructions? Â I've been
>> looking at various optimization options, and as far as I can tell it is at
>> least doing the following (non-contiguous):
>>
>> 00001e67     subl   $0x30,êx
>> 00001e6d     cmpl   $0x36,êx
>> 00001e70     jal   0x00001f67
>> 00001e76     movl   0x00000038(ëx,êx,4),êx
>> 00001e7d     addl   ëx,êx
>> 00001e7f     jmp   *êx
>>
>> So that's 6 instructions to set up and perform the indexed jump to which
>> the switch/case is being compiled.
>>
>> At the jump sites, typically another 2 instructions:
>>
>> 00001f60     movl   $0x0000000f,êx
>> 00001f65     jmp   0x00001fd2
>>
>> So that's a total of 8 instructions, with 2 taken and one typically
>> non-taken jump and one of the taken jumps computed, so probably not
>> predictable. Â I must be missing something obvious.
>
> The smallest (and likely fastest) would probably be the lookup table
> version:
>
> char hexCharToNibbleL(char nibble)
> {
> Â Â Â Â const char lt[255] = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
> 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
> 0xFF, 0xFF, 0xFF, 0xFF,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F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
> 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
> 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
> 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
> 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
> 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF };
> Â Â Â Â return lt[nibble];
> }
That last line needs to be:
return lt[(unsigned char)nibble];
otherwise, you're (at best) returning garbage for any non-ASCII characters.
--
Clark S. Cox III
email@hidden
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden