你沒有正確指定char
陣列,因爲它分配的類型太大了。這個怎麼樣,作爲一個例子:
#import <Foundation/Foundation.h>
int main(int argc, char *argv[]) {
NSAutoreleasePool *p = [[NSAutoreleasePool alloc] init];
// your example has longer hex value, truncated here for clarity...
unsigned char bytes[] = { 0x0F, 0x01, 0x21};
NSData *data = [NSData dataWithBytes:bytes length:3];
NSLog (@" Data is %@ ", data);
[p release];
}
打印2012-11-19 06:40:07.581 Untitled 2[12472:707] Data is <0f0121>
控制檯
或者,如果您的十六進制字節的字符串的形式,這樣的事情:
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[])
{
@autoreleasepool {
NSString *hexString = @"0x0f0121dd06a2d00503040705aa010ba2d0a2d0";
NSMutableData *data = [[NSMutableData alloc] init];
NSRegularExpression *expression = [NSRegularExpression regularExpressionWithPattern:@"[A-Fa-f0-9]{2}" options:0 error:NULL];
[expression enumerateMatchesInString:hexString options:0 range:NSMakeRange(0, hexString.length) usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop) {
int hex = (int)strtol([[hexString substringWithRange:result.range] UTF8String], NULL, 16);
printf("hex = %d\n",hex);
[data appendBytes:&hex length:1];
}];
NSLog(@"%s - data = %@",__FUNCTION__,data);
}
return 0;
}
哪打印2012-11-19 06:56:15.753 TestHexStringToBytes[12891:303] main - data = <0f0121dd 06a2d005 03040705 aa010ba2 d0a2d0>
到控制檯。
NSBum,非常感謝。有用。 :)。 – Whoami