On Aug 13, 2009, at 10:34, Chase Meadors wrote:

In other words, I might read one piece of data that is one byte: <FE>. I would want this to be read as -2. However, the current method would make the string "0xFE", then scan it to 0x000000FE, which is completely different.

I might then read a piece of data that is two bytes: <01 80> (little endian). This needs to be read as -32,767. However, the current method gives 0x00008001.

This is more of a C question. You could try something like:

        [[NSScanner scannerWithString:hexString] scanHexInt:&result];
        
        if ([self bytes] == 1)
                result = (int8_t) result;
        else if [self bytes] == 2)
                result = (int16_t) result;

        return [NSNumber numberWithInt:result];

IOW, you can use any C trick to sign-extend the shorter value.

P.S. Using NSScanner seems like a very long way round. Why not use a multiply-by-256-and-add technique on the raw bytes? Then all you need to do is to treat the first (i.e. the last) byte as signed, and all the other bytes as unsigned, and your sign-extension problem is solved too.


_______________________________________________

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

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:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com

Reply via email to