Created
December 13, 2012 15:16
-
-
Save Machx/4277049 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#import <Foundation/Foundation.h> | |
// Adapted from http://stackoverflow.com/a/11068850 | |
/** | |
* @brief convert a hexidecimal string to a signed long | |
* will not produce or process negative numbers except | |
* to signal error. | |
* | |
* @param hex without decoration, case insensative. | |
* | |
* @return -1 on error, or result (max sizeof(long)-1 bits) | |
*/ | |
long hexdec(const char *hex, int len) | |
{ | |
#pragma clang diagnostic push | |
#pragma clang diagnostic ignored "-Winitializer-overrides" | |
static const int hextable[] = { | |
[0 ... 255] = -1, // bit aligned access into this table is considerably | |
['0'] = 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, // faster for most modern processors, | |
['A'] = 10, 11, 12, 13, 14, 15, // for the space conscious, reduce to | |
['a'] = 10, 11, 12, 13, 14, 15 // signed char. | |
}; | |
#pragma clang diagnostic pop | |
int ret = 0; | |
if (len > 0) | |
{ | |
while (*hex && ret >= 0 && (len--)) | |
{ | |
ret = (ret << 4) | hextable[*hex++]; | |
} | |
} | |
else | |
{ | |
while (*hex && ret >= 0) | |
{ | |
ret = (ret << 4) | hextable[*hex++]; | |
} | |
} | |
return ret; | |
} | |
int main(int argc, char *argv[]) | |
{ | |
@autoreleasepool | |
{ | |
int d = hexdec("DEADBEEF", 4); | |
NSLog(@"%d 0x%X", d, d); | |
d = hexdec("DEADBEEF", 0); | |
NSLog(@"%d 0x%X", d, d); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment