我想将NSData
实例中的8个字节转换为包含2个项目的uint32_t
数组。我做了以下,但这不正确。
NSLog(@"Challenge data %@",dataChallenge);
uint32_t *data = (uint32_t *)dataChallenge.bytes;
NSLog(@"data0: %08x, data1: %08x", data[0], data[1]);
这就是结果:
Challenge data <3ce3e664 dafda14b>
data0: 64e6e33c, data1: 4ba1fdda
数据顺序不正确。
值应为:
Challenge data <3ce3e664 dafda14b>
data0: 3ce3e664, data1: dafda14b
答案 0 :(得分:2)
uint32_t * data =(uint32_t *)dataChallenge.bytes;
示例:
NSData *dataChallenge = [@"12345678" dataUsingEncoding:NSUTF8StringEncoding];
NSLog(@"dataChallenge: %@", dataChallenge);
uint32_t *data = (uint32_t *)dataChallenge.bytes;
NSLog(@"data0: %08x, data1: %08x", data[0], data[1]);
NSLog输出:
dataChallenge:&lt; 31323334 35363738&gt;
data0:34333231,data1:38373635
注意:字节是反转的,因为这是一个轻薄的机器
使用memcpy:
NSData *dataChallenge = [@"12345678" dataUsingEncoding:NSUTF8StringEncoding];
NSLog(@"dataChallenge: %@", dataChallenge);
uint32_t data[2];
memcpy(data, (uint32_t *)dataChallenge.bytes, dataChallenge.length);
NSLog(@"data0: %08x, data1: %08x", data[0], data[1]);
NSLog输出:
dataChallenge:&lt; 31323334 35363738&gt;
data0:34333231,data1:38373635
交换字节顺序:
NSLog(@"data0: %08x, data1: %08x", CFSwapInt32BigToHost(data[0]), CFSwapInt32BigToHost(data[1]));
NSLog输出:
data0:31323334,data1:35363738
注意:有关字节交换的更多组合,请参阅CFByteOrder.h。
答案 1 :(得分:0)
下面的逻辑将NSData完美地转换为整数。字节长度无关紧要。它只是有效。
NSData *data;
NSString *stringData = [data description];
stringData = [stringData substringWithRange:NSMakeRange(1, [stringData length]-2)];
unsigned dataAsInt = 0;
NSScanner *scanner = [NSScanner scannerWithString: stringData];
[scanner scanHexInt:& dataAsInt];