• Open Menu Close Menu
  • Apple
  • Shopping Bag
  • Apple
  • Mac
  • iPad
  • iPhone
  • Watch
  • TV
  • Music
  • Support
  • Search apple.com
  • Shopping Bag

Lists

Open Menu Close Menu
  • Terms and Conditions
  • Lists hosted on this site
  • Email the Postmaster
  • Tips for posting to public mailing lists
Arbitrary length ints from NSData
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Arbitrary length ints from NSData


  • Subject: Arbitrary length ints from NSData
  • From: Chase Meadors <email@hidden>
  • Date: Thu, 13 Aug 2009 12:34:47 -0500

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:@"X", 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 (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


  • Follow-Ups:
    • Re: Arbitrary length ints from NSData
      • From: Quincey Morris <email@hidden>
    • Re: Arbitrary length ints from NSData
      • From: Quincey Morris <email@hidden>
  • Prev by Date: Re: Trouble with NSColor
  • Next by Date: Re: Trouble with NSColor
  • Previous by thread: re: Core Data Crash on MOC Release
  • Next by thread: Re: Arbitrary length ints from NSData
  • Index(es):
    • Date
    • Thread