0

非常基本的问题。:(。我有一个十六进制值并试图适应 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>

我不确定我是否以正确的方式做这件事?友善的建议。

4

2 回答 2

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

于 2012-11-19T12:40:15.170 回答
0

这太大了,您使用的是 char 数组,但该数组仅包含一个字符,该字符会被截断,因此您不需要数组。
但是即使使用 long unsigned int 也没有足够的内存来存储这个值。使用 memset 代替,并计算每个字节的值。

于 2012-11-19T12:40:03.190 回答