Re: NSData and Primitives
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.