Re: Arbitrary length ints from NSData
Re: Arbitrary length ints from NSData
- Subject: Re: Arbitrary length ints from NSData
- From: Alastair Houghton <email@hidden>
- Date: Thu, 13 Aug 2009 19:34:29 +0100
On 13 Aug 2009, at 19:25, Chase Meadors wrote:
I'm a hobby programmer, and my first experience with programming was
the currency converter w/ interface builder example. As such, I
guess I'm learning "from the top down." I'm not very familiar with
straight C as I am with Objective-C. I'm afraid you'll have to
explain the multiply-by-256-and-add technique.
FWIW, I don't think that's the best way either. Why not just use the
OSRead*() functions from <libkern/OSByteOrder.h>? For instance,
#import <libkern/OSByteOrder.h>
...
const uint8_t *bytes = [myData bytes];
const uint8_t *ptr = bytes;
// Read a 32-bit signed int
int32_t fourBytes = OSReadLittleInt32 (ptr, 0);
ptr += 4;
// Read a 16-bit signed int
int16_t twoBytes = OSReadLittleInt16 (ptr, 0);
ptr += 2;
// Read an 8-bit signed int
int8_t oneByte = (int8_t)*ptr++;
You *could* use offsets instead of pointers if you want---e.g.
uintptr_t offset = 0;
// Read a 32-bit signed int
int32_t fourBytes = OSReadLittleInt32 (bytes, offset);
offset += 4;
// Read a 16-bit signed int
int16_t twoBytes = OSReadLittleInt16 (bytes, offset);
offset += 2;
// Read an 8-bit signed int
int8_t oneByte = (int8_t)bytes[offset++];
This way, you don't need to worry about endianness and there's no need
for any shifting (which is the more sensible alternative to
multiplications by 256).
Kind regards,
Alastair.
--
http://alastairs-place.net
_______________________________________________
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