Hi All,

I'm having a problem reading numbers from some raw data I need to read. The data encodes numbers in little-endian format. I am defining a category on NSData to accomplish this.

- (NSNumber *)interpretAsSingleNumber {
        
        NSMutableString *hexString = [NSMutableString string];
        
        unsigned char *bytes = [self bytes];
        
        for (int i = [self length] - 1;  i > -1;  i --) {
                
                [hexString appendFormat:@"%02X", bytes[i]];
                
        }
        
        [hexString insertString:@"0x" atIndex:0];
        
        unsigned int result;
        [[NSScanner scannerWithString:hexString] scanHexInt:&result];
        
        return [NSNumber numberWithInt:result];
        
}

The problem here is that NSScanner can only scan 32-bit integers. The numbers in the data I'm trying to read can be either 8 or 16 bits. I'm given the information as to exactly what range in the data represents a certain number, so I could see whether it is one or two bytes long, but how can I accomplish getting an int from this data that IS the length of the data.

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.

Any hints as to how I might accomplish this? Thanks!
_______________________________________________

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