Created
March 17, 2009 05:29
-
-
Save qwzybug/80292 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
@interface NSData (NSData_HexAdditions) | |
- (NSData *)dataFromHexString; | |
@end | |
#define IS_HEX(c) ((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >='A' && c <= 'F')) | |
@implementation NSData (NSData_HexAdditions) | |
/* | |
* Takes an NSData encoding an ASCII string representing hexadecimal data, | |
* and reads it into an NSData of the represented bytes. | |
* Ignores non-hex characters, might drop the last nibble. | |
* E.g., "ABC\r\nDE" -> 0xABCD | |
*/ | |
- (NSData *)dataFromHexString; | |
{ | |
const unsigned char *bytes = [self bytes]; | |
// Read all hexadecimal characters into array | |
unsigned char *hexChars = calloc(sizeof(char), [self length]); | |
const unsigned char *s; | |
int charCount = 0; | |
for (s = bytes; s < bytes + [self length]; s++) { | |
if (IS_HEX(*s)) { | |
hexChars[charCount++] = *s; | |
} | |
} | |
// Convert pairs of hexadecimal characters to bytes | |
unsigned char *dataBuffer = calloc(sizeof(char), charCount / 2); | |
char c[3] = "XX"; | |
int byteCount = 0; | |
for (s = hexChars; s < hexChars + charCount - 1; s += 2) { | |
c[0] = s[0]; | |
c[1] = s[1]; | |
dataBuffer[byteCount++] = (char)(strtol(c, NULL, 16)); | |
} | |
NSData *data = [NSData dataWithBytes:dataBuffer length:byteCount]; | |
free(dataBuffer); | |
free(hexChars); | |
return data; | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment