Re: Does NSData rearrange the order of bits?
Re: Does NSData rearrange the order of bits?
- Subject: Re: Does NSData rearrange the order of bits?
- From: Peter Duniho <email@hidden>
- Date: Mon, 30 Nov 2009 12:38:20 -0800
On Nov 30, 2009, at 11:27 AM, Brad Gibbs wrote:
Hi,
I'm doing bit-packing via a C function. Logging the bits of the C
function shows the expected result. If I create a string with a hex
value format, I get the correct hex string, but, if I try to put the
bytes into an NSData object with [NSData dataWithBytes: length], the
order of the bits changes. All of the right elements are there, but
they're in the wrong order (target data should be f0000651, as shown
in the Target string is ... log).
The output looks correct to me. In particular:
[...]
NSString *tgtString = [NSString stringWithFormat:@"%x", tgtBinary];
Here (above), you ask NSString to interpret the bytes passed as a
single integer value as exactly that: an integer value, formatted as
hexadecimal.
NSData *tgtData = [NSData dataWithBytes: &tgtBinary length:
sizeof(tgtBinary)];
But here (above), you as NSData to interpret the bytes passed as a
sequence of bytes, in the order in which they appear in memory.
Presumably you are executing this code on an Intel Mac, where the byte
ordering is little-endian. This means the least-significant byte
appears first in memory order. So, that's the order you see when you
get NSData to produce a string of the bytes it contains.
[...]
If NSData is rearranging the bits, is there some way to prevent this?
To me, a more interesting question is: do you really need some way to
prevent this? What exactly are you doing with the NSData later, and
why is it important to you that the byte order be some specific
endianness?
If you really need control over endianness, you can use the Core
Endian API (http://developer.apple.com/mac/library/documentation/Carbon/Reference/CoreEndianReference/
) to always make sure the bytes are of some particular endianness
regardless of the computer's native format. But it may be that the
endianness doesn't matter. You should be sure you know the
difference, and what applies to your own code.
Pete
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden