forked from jerrykrinock/CategoriesObjC
-
Notifications
You must be signed in to change notification settings - Fork 0
/
NSData+HexString.m
48 lines (39 loc) · 1.16 KB
/
NSData+HexString.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#import "NSData+HexString.h"
char ASCIIHexCharacterForNibble(short nibble, BOOL uppercaseLetters) {
char answer ;
short offset ;
if (nibble < 10) {
offset = 0x30 ;
}
else if (uppercaseLetters) {
offset = 0x37 ;
}
else {
offset = 0x57 ;
}
answer = (char)(nibble + offset) ;
return answer ;
}
@implementation NSData (HexString)
- (NSString*)lowercaseHexString {
// Maybe this could have been done easier by chunking it up into
// integer-size numbers and using format strings with %x, but
// that might have raised endian issues. I think this way will
// be endian-agnostic.
int i ;
char hashCString[33] ;
for (i=0; i<[self length]; i++) {
NSData* dataChunk = [self subdataWithRange:NSMakeRange(i, 1)] ;
unsigned char oneByte ;
[dataChunk getBytes:&oneByte] ;
int subscript ;
subscript = 2*i ;
hashCString[subscript] = ASCIIHexCharacterForNibble((oneByte & 0xf0) >> 4, NO) ;
subscript = 2*i+1 ;
hashCString[subscript] = ASCIIHexCharacterForNibble(oneByte & 0x0f, NO) ;
}
hashCString[32] = 0 ; // null termination
NSString* hashedString = [[NSString alloc] initWithUTF8String:hashCString] ;
return [hashedString autorelease] ;
}
@end