views:

72

answers:

2

Hi all,

I have a NSData object with 4 bytes length. I know this 4 bytes construcuts a positive integer. How should I get the int from those NSdata object?

+3  A: 

If you know the endianness matches the current system:

x = *(const UInt32 *)[theData bytes];

If you know the endianness is backwards, follow that with:

x = Endian32_Swap( x );

If you are not sure of the source and target endianness, you should probably find another way to pass the data.

drawnonward
You can use `EndianU32_BtoN` (or `EndianS32_BtoN` for signed) if you know the source is big-endian, and `EndianU32_LtoN` if you know it's little-endian. This means you don't have to know the endianness of the running system.
Matthew Flaschen
- (void) onSocket:(AsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag{//I know this data is 4bytes lengthNSString *msgReceived = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease];//I want to get the int from the NSData}
charith
A: 
int32_t value; // make unsigned if needed. 
[myData getBytes: &value];
Matthew Flaschen
`getBytes:` is deprecated in OS X 10.6 and iPhone OS 4.0, so one may use [`getBytes:length:`](http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSData_Class/Reference/Reference.html#//apple_ref/occ/instm/NSData/getBytes:length:) to avoid warnings.
dreamlax
Thanks for reply.but this return a huge integer value like 865465934. I have stuck with this for almost 1 day now.
charith
@charith, it sounds like the endianness is wrong, try swapping it with [`NSSwapLittleIntToHost`](http://developer.apple.com/mac/library/documentation/cocoa/reference/foundation/Miscellaneous/Foundation_Functions/Reference/reference.html#//apple_ref/c/func/NSSwapLittleIntToHost)
dreamlax
@charith, see my comment above. It will help if you give more info.
Matthew Flaschen
@dreamlax, I'm trying. I will let you know the results for sure. Thanks again.
charith
- (void) onSocket:(AsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag{//I know this data is 4bytes lengthNSString *msgReceived = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease];//I want to get the int from the NSData}
charith