您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>
到控制台。