• 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
Re: Arbitrary length ints from NSData
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Arbitrary length ints from NSData


  • Subject: Re: Arbitrary length ints from NSData
  • From: Alastair Houghton <email@hidden>
  • Date: Thu, 13 Aug 2009 19:34:29 +0100

On 13 Aug 2009, at 19:25, Chase Meadors wrote:

I'm a hobby programmer, and my first experience with programming was the currency converter w/ interface builder example. As such, I guess I'm learning "from the top down." I'm not very familiar with straight C as I am with Objective-C. I'm afraid you'll have to explain the multiply-by-256-and-add technique.

FWIW, I don't think that's the best way either. Why not just use the OSRead*() functions from <libkern/OSByteOrder.h>? For instance,


  #import <libkern/OSByteOrder.h>

  ...

  const uint8_t *bytes = [myData bytes];
  const uint8_t *ptr = bytes;

  // Read a 32-bit signed int
  int32_t fourBytes = OSReadLittleInt32 (ptr, 0);
  ptr += 4;

  // Read a 16-bit signed int
  int16_t twoBytes = OSReadLittleInt16 (ptr, 0);
  ptr += 2;

  // Read an 8-bit signed int
  int8_t oneByte = (int8_t)*ptr++;

You *could* use offsets instead of pointers if you want---e.g.

  uintptr_t offset = 0;

  // Read a 32-bit signed int
  int32_t fourBytes = OSReadLittleInt32 (bytes, offset);
  offset += 4;

  // Read a 16-bit signed int
  int16_t twoBytes = OSReadLittleInt16 (bytes, offset);
  offset += 2;

  // Read an 8-bit signed int
  int8_t oneByte = (int8_t)bytes[offset++];

This way, you don't need to worry about endianness and there's no need for any shifting (which is the more sensible alternative to multiplications by 256).

Kind regards,

Alastair.

--
http://alastairs-place.net



_______________________________________________

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


References: 
 >Arbitrary length ints from NSData (From: Chase Meadors <email@hidden>)
 >Re: Arbitrary length ints from NSData (From: Quincey Morris <email@hidden>)
 >Re: Arbitrary length ints from NSData (From: Chase Meadors <email@hidden>)

  • Prev by Date: Re: Arbitrary length ints from NSData
  • Next by Date: Re: Arbitrary length ints from NSData
  • Previous by thread: Re: Arbitrary length ints from NSData
  • Next by thread: Re: Arbitrary length ints from NSData
  • Index(es):
    • Date
    • Thread