Reputation: 3851
So, take an unsigned int, say 4286578687.
From this site: http://www.mathsisfun.com/binary-decimal-hexadecimal-converter.html
I get the hex value to be: FF7FFFFF
However, if I put that int into NSData like so:
//The unsigned int is unsignedInt and its length is unsignedLength
NSData *thisData = [NSData dataWithBytes:&unsignedInt length:unsignedLength];
And then use the description method, which supposedly returns the data's hex value as a string:
NSLog(@"data as hex: %@", [thisData description]);
The output is:
data as hex: <ffff7fff>
Which on the same website evaluates to 4294934527.
So it seems like NSData is using some non-standard hex format. Can anyone tell me how to get back to the real hex format?
Upvotes: 0
Views: 352
Reputation: 318774
You are seeing a difference between storing the bytes of the unsigned int
in big-endian versus little-endian.
If you want to guarantee that the output of the NSData
is in big-endian format then you should do the following:
unsigned int x = 4286578687;
unsigned int big = NSSwapHostIntToBig(x);
NSData *thisData = [NSData dataWithBytes:&big length:sizeof(big)];
NSLog(@"data as hex: %@", thisData);
This logs the expected result of data as hex: <ff7fffff>
.
This code will work on any processor type and always give you the result in big-endian format.
When going back the other way you would need to use the NSSwapBigIntToHost
function to ensure the big-endian data is properly converted to the local format.
Upvotes: 2
Reputation: 8247
You can try something like this :
NSInteger i = 4286578687;
NSLog(@"hex : %@", [NSString stringWithFormat:@"%X", i]);
// Result
>>> hex : FF7FFFFF
Upvotes: 0