Created
March 24, 2010 05:30
-
-
Save wookay/342010 to your computer and use it in GitHub Desktop.
hexToBytes
This file contains hidden or 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 NSString (NSStringHexToBytes) | |
-(NSData*) hexToBytes ; | |
@end | |
@implementation NSString (NSStringHexToBytes) | |
-(NSData*) hexToBytes { | |
NSMutableData* data = [NSMutableData data]; | |
int idx; | |
for (idx = 0; idx+2 <= self.length; idx+=2) { | |
NSRange range = NSMakeRange(idx, 2); | |
NSString* hexStr = [self substringWithRange:range]; | |
NSScanner* scanner = [NSScanner scannerWithString:hexStr]; | |
unsigned int intValue; | |
[scanner scanHexInt:&intValue]; | |
[data appendBytes:&intValue length:1]; | |
} | |
return data; | |
} | |
@end | |
/// example | |
unsigned char bytes[] = { 0x11, 0x56, 0xFF, 0xCD, 0x34, 0x30, 0xAA, 0x22 }; | |
NSData* expectedData = [NSData dataWithBytes:bytes length:sizeof(bytes)]; | |
NSLog(@"data %@", [@"1156FFCD3430AA22" hexToBytes]); | |
NSLog(@"expectedData isEqual:%d", [expectedData isEqual:[@"1156FFCD3430AA22" hexToBytes]]); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment