Thread: read/write a floating point value

  1. #1
    Registered User
    Join Date
    Apr 2003

    read/write a floating point value


    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.


  2. #2
    End Of Line Hammer's Avatar
    Join Date
    Apr 2002
    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 :
    When all else fails, read the instructions.
    If you're posting code, use code tags: [code] /* insert code here */ [/code]

  3. #3
    Registered User
    Join Date
    Apr 2003
    Yeh that would of course be a solution to the problem.
    I will try that out.


Popular pages Recent additions subscribe to a feed

Similar Threads

  1. How accurate is the following...
    By emeyer in forum C Programming
    Replies: 22
    Last Post: 12-07-2005, 12:07 PM
  2. checking for floating point number
    By ssharish2005 in forum C Programming
    Replies: 6
    Last Post: 10-18-2005, 08:14 PM
  3. floating point question
    By Eric Cheong in forum C Programming
    Replies: 8
    Last Post: 09-10-2004, 10:48 PM
  4. 2 questions about floating point and %
    By ams80 in forum C Programming
    Replies: 2
    Last Post: 08-14-2002, 10:55 AM
  5. Replies: 2
    Last Post: 09-10-2001, 12:00 PM