]> git.saurik.com Git - apple/security.git/blobdiff - Security/libsecurity_transform/NSData+HexString.m
Security-57031.1.35.tar.gz
[apple/security.git] / Security / libsecurity_transform / NSData+HexString.m
diff --git a/Security/libsecurity_transform/NSData+HexString.m b/Security/libsecurity_transform/NSData+HexString.m
new file mode 100644 (file)
index 0000000..b68c90d
--- /dev/null
@@ -0,0 +1,31 @@
+//
+//  NSData+HexString.m
+//  libsecurity_transform
+//
+//  Copyright (c) 2011,2014 Apple Inc. All Rights Reserved.
+//
+
+#import "NSData+HexString.h"
+
+@implementation NSData (HexString)
+
+// Not efficent
++(id)dataWithHexString:(NSString *)hex
+{
+       char buf[3];
+       buf[2] = '\0';
+       NSAssert(0 == [hex length] % 2, @"Hex strings should have an even number of digits (%@)", hex);
+       unsigned char *bytes = malloc([hex length]/2);
+       unsigned char *bp = bytes;
+       for (CFIndex i = 0; i < [hex length]; i += 2) {
+               buf[0] = [hex characterAtIndex:i];
+               buf[1] = [hex characterAtIndex:i+1];
+               char *b2 = NULL;
+               *bp++ = strtol(buf, &b2, 16);
+               NSAssert(b2 == buf + 2, @"String should be all hex digits: %@ (bad digit around %ld)", hex, i);
+       }
+       
+       return [NSData dataWithBytesNoCopy:bytes length:[hex length]/2 freeWhenDone:YES];
+}
+
+@end