非常基本的问题。 :(。我有一个十六进制值,并试图适应NSData,和 尝试了以下。
unsigned char bytes [] = {0x0f0121dd06a2d00503040705aa010ba2d0a2d0};
NSData *data = [NSData dataWithBytes: bytes length:19];
NSLog (@" DAta is %@ ", data);
我收到以下警告
34:37: warning: integer constant is too large for its type
34: warning: large integer implicitly truncated to unsigned type
数据打印如下:
NSDataExample[36136:707] DAta is <d028e08c 7fff7f00 00000000 00000000 0008fc>
我不确定我是否以正确的方式做到了?好心劝告。
答案 0 :(得分:1)
您似乎没有正确分配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>
打印到控制台。
答案 1 :(得分:0)
这太大了,你使用的是char数组,但是数组只包含一个字符,它会被截断,所以你不需要数组。
但即使使用long unsigned int,也没有足够的内存来存储该值。请使用memset,并计算每个字节的值。