views:

281

answers:

4

How can I read and write ints from/to NSStreams? I know I can read bytes individually, but I want to take endianness into account. Java has DataStreams for these cases, is there something equivalent in Obj-C?

+2  A: 

There’s nothing like that for you in the streams. There are the standard ntoh*/hton* suite of functions to convert from network to host order and back.

Ben Stiglitz
A: 

There is NSInputStream read:maxLength: and NSOutputStream write:maxLength:

http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSInputStream_Class/Reference/Reference.html#//apple_ref/doc/uid/20001982-BAJCCBCH

http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSOutputStream_Class/Reference/Reference.html#//apple_ref/doc/uid/20001983-BAJCCBCH

derrdji
Yes, but they read a sequence of bytes to a byte array. I want to read complete ints and have the bytes ordered according to the plataform endianness.
Marco Mustapic
A: 

I don't know of an objc equivalent, but taking things into your own hands is not hard:

Write your ints one byte at a time, using shift operators, and read and reconstruct them similarly.

If you want to write in big endian format, do something like this:

for(int i = 0; i < 4; i++) WriteAByteLOL((n >> (8*(4-i-1))) & 0xff);

Reverse the loop order if you want little endian.

For reading, do this (assumes data lives in 4 byte array b):

unsigned int n = 0;
for(int i = 0; i < 4; i++) n = (n<<8) | b[i];

Easy!

Rhythmic Fistman
A: 

Off-hand, I don't know if there's a socket-layer implementation.

In Objective C, have a look at the Core Endian Reference manual.

Or have a look at the C-level XDR routines that are available in Mac OS X; the External Data Representation (XDR) routines are a part of a common Unix-level RPC environment.

Or you can swizzle your own bytes.

gSOAP or XML or other such are also layered into applications here, too; looking to trump the network traffic. (I'd tend to look to avoid rolling my own protocol, if I can manage that.)

And regardless of what you're doing with this stuff, remember to stick a version number into the byte stream within whatever network protocol you're implementing here.

Stephen Hoffman