]> git.saurik.com Git - apple/security.git/blame - libsecurity_transform/NSData+HexString.m
Security-55471.14.18.tar.gz
[apple/security.git] / libsecurity_transform / NSData+HexString.m
CommitLineData
b1ab9ed8
A
1//
2// NSData+HexString.m
3// libsecurity_transform
4//
5// Copyright (c) 2011 Apple, Inc. All rights reserved.
6//
7
8#import "NSData+HexString.h"
9
10@implementation NSData (HexString)
11
12// Not efficent
13+(id)dataWithHexString:(NSString *)hex
14{
15 char buf[3];
16 buf[2] = '\0';
17 NSAssert(0 == [hex length] % 2, @"Hex strings should have an even number of digits (%@)", hex);
18 unsigned char *bytes = malloc([hex length]/2);
19 unsigned char *bp = bytes;
20 for (CFIndex i = 0; i < [hex length]; i += 2) {
21 buf[0] = [hex characterAtIndex:i];
22 buf[1] = [hex characterAtIndex:i+1];
23 char *b2 = NULL;
24 *bp++ = strtol(buf, &b2, 16);
25 NSAssert(b2 == buf + 2, @"String should be all hex digits: %@ (bad digit around %d)", hex, i);
26 }
27
28 return [NSData dataWithBytesNoCopy:bytes length:[hex length]/2 freeWhenDone:YES];
29}
30
31@end