Re: Arbitrary length ints from NSData
Re: Arbitrary length ints from NSData
- Subject: Re: Arbitrary length ints from NSData
- From: Quincey Morris <email@hidden>
- Date: Thu, 13 Aug 2009 11:50:09 -0700
On Aug 13, 2009, at 11:25, Chase Meadors wrote:
I'm afraid you'll have to explain the multiply-by-256-and-add
technique.
I mean something like this (untested):
unsigned char *bytes = [self bytes];
int byteIndex = [self length];
int result = 0;
BOOL firstByte = YES;
while (byteIndex--) {
if (firstByte) {
result = (signed char *) bytes [byteIndex]; // signed the first
time
firstByte = NO;
}
else
result = result * 0x100 + bytes [byteIndex]; // unsigned the rest
of the times
}
return [NSNumber numberWithInt: result];
BTW, I didn't notice that you'd originally declared 'result' as
unsigned int, so my first suggestion wouldn't have have worked unless
you also changed 'result' to a signed int.
P.S. I see Alastair gave you a mostly better answer already. However,
I'll point out that if you have any *3-byte* numbers (I see "arbitrary
length ints" in the subject line) you're not going to find an
OSReadLittleInt24 to help you.
_______________________________________________
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