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?
views:
281answers:
4There’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.
There is NSInputStream read:maxLength: and NSOutputStream write:maxLength:
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!
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.