In Xcode 5.0.2 on OS X 10.9.1:

uint64_t data = 0x6ffa9e58938d7f5d;
NSData *nsdataObj = [NSData dataWithBytes:&data length:8];
NSLog(@"%@", nsdataObj);

Output:

<5d7f8d93 589efa6f>

How/why is the data getting reversed?

有帮助吗?

解决方案 2

Because Endianness apparently. (Thanks @Hot Licks and @Josh Caswell!) Solved the issue by using the Core Foundation byte order function CFSwapInt64.

其他提示

In this brave new world of Intel Macintoshes*, your integers are stored in memory in an absolutely bizzare fashion known as "little-endian byte order". That means that, unlike the more reasonable, human-readable format in which you wrote your number, the Least Significant Bytes, or the bytes of the lowest magnitude, are actually sorted to the beginning of the data. (In the case of your data, the LSB is 0x5d, followed by 0x7f, and so on up.)

This doesn't change the value of the integer; if you use the value as an integer, the computer knows how to read it back appropriately. On the other hand, NSData just scoops the bytes out as they lie in memory, so you see the little-endian order when you print it.

If you need to change the order before creating the NSData to the more natural big-endian order -- as Woz intended -- you can use the appropriate Foundation Byte Ordering function.

Check out this Big Nerd Ranch article for more.


*Okay, not really that new anymore.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top