Thursday, February 10, 2011

read a int from a file wrote by java's writeInt method in C++?

How would one go about doing this? Also, is there an easy way to do it? Using a lib like Boost or something?

  • Ideas:

    1. Read it in as straight binary, then convert/interpret bytes as necessary. So if Java wrote out 4 bytes for the int, then you read in 4 bytes. If there is any endian-ness to change then do that, then cast (or copy) the byte array to a c++ int
    2. If you can change the Java code, you could write it out as something common that C++ can read like UTF-8 text or ascii, or Google Protocol Buffers format or something else.
    From Alex Black
  • The DataOutputStream which writes out the int writes out a 4 byte int, with the high bytes first. Read into char*, reinterpret and if you need to convert the byte order use ntohl.

    ifstream is;
    is.open ("test.txt", ios::binary );
    char* pBuffer = new char[4];
    
    is.read (pBuffer, 4);
    is.close();
    
    int* pInt = reinterpret_cast<int*>(pBuffer);
    int myInt = ntohl(*pInt); // This is only required if you are on a little endian box
    delete [] pBuffer;
    
    Pavel Minaev : All well and good until you hit a platform where `sizeof(int) != 4`. Or a one where integers are ones' complement or sign-bit, and not two's complement (all allowed by ISO C99).
    Pavel Minaev : ... as well as ISO C++
    anio : On what platform are integers ones' complement or sign-bit? I would like to know.
    Steve Jessop : @mamin: The PDP-1 used one's complement, and there are still three of them in existence (plus emulators).
    From anio
  • The only cross-platform way to do it is to read it byte by byte (that is, char by char), and build an integer out of them. You'd want to use long, because int is not guaranteed to be wide enough to hold a 32-bit value. I'll assume you've read the bytes into a char[4] array here (other answers have already demonstrated how to do that):

    char bytes[4];
    ...
    long n = (long(bytes[0]) << 24) | (long(bytes[1]) << 16) |
             (long(bytes[2]) << 8)  |  long(bytes[3])
    

0 comments:

Post a Comment