Re: Arbitrary length ints from NSData
Re: Arbitrary length ints from NSData
- Subject: Re: Arbitrary length ints from NSData
- From: Chase Meadors <email@hidden>
- Date: Thu, 13 Aug 2009 22:10:17 -0500
On Aug 13, 2009, at 1:50 PM, Quincey Morris wrote:
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.
Yes, thanks for the help both of you. The OSRead functions are very
convenient, but I settled on your solution because I do have some 3-
byte numbers. Works like a charm!
_______________________________________________
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
_______________________________________________
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