tags:

views:

57

answers:

3

I have a program in Java that needs to write a file with integers of 8, 16, 32 and 64 bits and floating point numbers of 16, 32 and 64 bits. This file needs to be read by a program in C (and vice-versa). These programs are used in different type of machines, so the file needs to be independent of little or big endian.

I am looking for a library in Java and in C for doing this. The library needs to be compact, because this will be used also in a micro-controller.

note: At the moment, I am implementing the functions myself, and it works fine (so, no need to give me an ad-hoc solution). note: I am aware that I could write the numbers in a human readable format, and use scanf to read them; I prefer not to use this solution now, because it is slower and takes more place.

+3  A: 

Google's Protocol Buffers seem like what you're after.

caf
It looks great, thanks! However, it is not a compact library, definitively not suited for a micro-controller I guess.I installed and played with it, and it seems that a 32 bit number is not serialized in 4 bytes, but in a kind of decimal format, so the number 9 would be serialized in one byte, and the number 2^31 would be serialized in 12 bytes. Moreover, there is not a C version (only C++).Are you aware of an alternative?
David Portabella
@David Portabella: There's [also a C version](http://code.google.com/p/protobuf-c/). Did you notice the [optimize for code size option](http://code.google.com/apis/protocolbuffers/docs/reference/java-generated.html) in the Java code generator?
caf
thanks! I am checking out the C version. hope that the code size is small enough to put it into a microcontroller.
David Portabella
+2  A: 

On the Java side, you can just use DataOutputStream, it's guaranteed to use big endian format aka network byte order. On the C side, you can use the ntohl() and ntohs() functions to convert network byte order to host byte order.

Michael Borgwardt
thanks, that's a very compact for integers.
David Portabella
@David: DataOutputStream does everything, and ntohl() and ntohs() should work for floats as well. The only problem is that they only do 16 and 32 bits, there doesn't seem to be a standard function for 64 bit values (for single-byte values, there isn't anything to do anyway).
Michael Borgwardt
A: 

One possibility would be to use Sun's XDR format. Oddly, I don't believe Java ships with support for it, but if you look around, it's easy to find. Sun does include an XDR library with Solaris; if you're not using Solaris, it's easy to find implementations for C as well.

Jerry Coffin