read/write a floating point value [Archive] - C Board

PDA

View Full Version : read/write a floating point value


champ
09-13-2003, 11:52 AM
Hi

Im currently writing a server/client system. I use c++ on the server and java on the client.

Therefore I want to write a protocol that handles the byte orders and other communication issues. For example to write a integer onto the socket stream, I do like this:




void writeInt(int i)
{
write(socket, (void*)((i >> 24) & 0xff), sizeof(char));
write(socket, (void*)((i >> 16) & 0xff), sizeof(char));
write(socket, (void*)((i >> 8) & 0xff), sizeof(char));
write(socket, (void*)(i & 0xff), sizeof(char));
}



This would convert it from little-endian to big-endian. So this works. The problem is if I want to write/read a float or a double. First of all, you can't use the shift operator on a floating-point value. I know on java they have readDouble & writeDouble functions in the DataInput/DataOutput interfaces. I think that the writeDouble function are implemented in a way that they convert the double to a long and then write it over the network. And the readDouble converts it back again.

Maybe I have to do something similar. I know I have to do some bit manipulation, but I don't know what. The problem with java approach, is of course that the size of a long is 4 bytes on the linux box(c++), but on the client(java) it is 8 bytes. So I might have deal with that problem as well.

Anyone who have struggled with something similar?. I will be very thankfull for any help.

Thanks

Hammer
09-13-2003, 06:08 PM
Write the numbers to the socket in plain text, with a terminator of some sort. Like:

123.987\0 (\0 being a 0x00 byte)

Then use the other ends string to number conversion routines.

There are functions for doing to bit manipulation for longs etc :
http://www.rt.com/man/htonl.3.html

champ
09-14-2003, 12:09 AM
Yeh that would of course be a solution to the problem.
I will try that out.

Thanks