Last active
August 29, 2015 14:02
-
-
Save ajonnet/c3a1792681bb3d352f93 to your computer and use it in GitHub Desktop.
Generates NSData instance for given hex String. Hex string is looked up from 0th index to nth index, for hex literals and accordingly NSData instance is generated.
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
-(NSData *) NSDataFromHexString:(NSString *) hexstr | |
{ | |
NSMutableData *data = [[NSMutableData alloc] init]; | |
NSString *inputStr = [hexstr uppercaseString]; | |
NSString *hexChars = @"0123456789ABCDEF"; | |
Byte b1,b2; | |
b1 = 255; | |
b2 = 255; | |
for (int i=0; i<hexstr.length; i++) { | |
NSString *subStr = [inputStr substringWithRange:NSMakeRange(i, 1)]; | |
NSRange loc = [hexChars rangeOfString:subStr]; | |
if (loc.location == NSNotFound) continue; | |
if (255 == b1) { | |
b1 = (Byte)loc.location; | |
}else { | |
b2 = (Byte)loc.location; | |
//Appending the Byte to NSData | |
Byte *bytes = malloc(sizeof(Byte) *1); | |
bytes[0] = ((b1<<4) & 0xf0) | (b2 & 0x0f); | |
[data appendBytes:bytes length:1]; | |
b1 = b2 = 255; | |
} | |
} | |
return data; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment