• 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: NSData and Primitives
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: NSData and Primitives


  • Subject: Re: NSData and Primitives
  • From: Aram Greenman <email@hidden>
  • Date: Sun, 9 Jun 2002 18:22:42 -0700

On Sunday, June 9, 2002, at 04:46 PM, Buzz Andersen wrote:

Hello all,
I am a long-time Java programmer who is currently trying to very hard to
"grok" the whole Objective C/Cocoa way of doing things, so please bear with
me if this question seems too elementary :-)...

Basically, what I have is a file containing a custom binary data format,
from which I would like to read various primitive data types--longs, Unicode
Strings, etc. Now, I have already done Java programs which do this very
thing using methods like "readLong()" in the java.io.DataInputStream class,
but I am unsure of the best way to accomplish a similar thing using NSData,
NSFileHandle, etc.

Basically, my attempts so far go something like this:

NSFileHandle *file;
NSData *buffer;
unsigned char[4] bytes;
unsigned long number;

file = [NSFileHandle fileHandleForReadingAtPath: theFile];
buffer = [file readDataOfLength: sizeof(long)];
[buffer getBytes: bytes];
memcpy(&number, &bytes, sizeof(long));

You can simplify this considerably:


[[file readDataOfLength:sizeof(long)] getbytes:&number];

but you should add this:

number = NSSwapLittleLongToHost(number);

or

number = NSSwapBigLongToHost(number);

depending if the file is little- or big-endian. Also, -[NSFileHandle readDataOfLength:] throws an exception on error, so you should catch that.


Is this the best way to do it, or is there a better way using Foundation or
Appkit classes? Is this even a reliable way of doing it (I'm kind of having
trouble figuring out if this method is working properly--the results don't
seem right to me).

I bet the file is little-endian.


a.
_______________________________________________
cocoa-dev mailing list | email@hidden
Help/Unsubscribe/Archives: http://www.lists.apple.com/mailman/listinfo/cocoa-dev
Do not post admin requests to the list. They will be ignored.

  • Follow-Ups:
    • Re: NSData and Primitives
      • From: Buzz Andersen <email@hidden>
References: 
 >NSData and Primitives (From: Buzz Andersen <email@hidden>)

  • Prev by Date: Re: Objective-C Specification
  • Next by Date: Re: NSData and Primitives
  • Previous by thread: NSData and Primitives
  • Next by thread: Re: NSData and Primitives
  • Index(es):
    • Date
    • Thread