[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
NSData, hex, and decimal
- Subject: NSData, hex, and decimal
- From: bootc at mac.com (Chris Boot)
- Date: Fri Mar 15 12:23:06 2002
- In-reply-to: <B8B7A2FF.7FC%klevn@mac.com>
Hi,
> Ok I'm reading packets of info from a server. I can decode them fine until
> I reach a strange barrier: 127.
>
> Why? As soon as I receive 0x80 and try to use this code I get negative
> numbers... Why is it doing this?
>
> [data getBytes:&packetLength range:NSMakeRange(2, 1)];
> NSLog(@"Length: %c %i data:%i",packetLength,packetLength, [data
> length]);
You must be using signed chars instead of unsigned chars. If you just
define your buffer as a char array, you will be default get signed chars.
The characteristic of signed variable types is that if you switch on the
highest bit, it will give negative numbers. 0x80 in binary is 0b10000000,
and as you can see the sign bit is on. If you want to get only positive
numbers, define / cast your buffer as an unsigned char array. If you want
to put it through printf, use the %uc template (the u means unsigned). This
would turn your code into:
unsigned char packetLength;
[data getBytes:&packetLength range:NSMakeRange(2, 1)];
NSLog(@"Length: %uc %ui data:%ui",packetLength,packetLength, [data length]);
Note that I haven't tested this at all, I'm just doing it all from memory.
HTH,
--
Chris Boot
bootc@xxxxxxx
"The keyboard is missing - Press any key to continue."