Yahoo Answers is shutting down on May 4th, 2021 (Eastern Time) and the Yahoo Answers website is now in read-only mode. There will be no changes to other Yahoo properties or services, or your Yahoo account. You can find more information about the Yahoo Answers shutdown and how to download your data on this help page.
Trending News
How can I send an array of floats from c to Java over socket?
Can someone point me to an example or show me one of there own?
I should note the byte order on the c side is little endian and on the Java is big endian.
2 Answers
- husoskiLv 75 years agoFavorite Answer
The usual solution for data portability is to convert the data to plain ASCII text for transmission. That's what the JSON answer suggested earlier would accomplish, for example. Something far simpler would work and would be easy to create in C and easy to read in Java without hauling in a library. Use sprintf() to format the array as a stream of space-separated ASCII numbers on the C side and a java.util.Scanner object's nextFloat() method on the input side.
You might try something like that to see if it will work. However...
One thing that's slightly odd is your choice of float as the data type. There aren't many reasons for using float instead of double, and they pretty much always involve either storage or time being more critical that precision. ASCII conversion will take more CPU time and more transmission time.
If you want to experiment with sending raw binary data, take a look at using java.nio.channels.SocketChannel (or ServerSocketChannel, if a server socket is needed on the Java side) and java.nio.ByteBuffer. That will let you read in a stream of bytes and interpret them as a stream of binary floats. It would be easier in this case to make it the the C program's responsibility to match the Java byte order.
You can byte-reverse a float (assuming 4-byte IEEE and a "normal" C compiler) in place with:
void reverse( float *fp )
{
.... char *cp = (char *) fp;
.... char t;
.... t = cp[0]; cp[0] = cp[3]; cp[3] = t;
.... t = cp[1]; cp[1] = cp[2]; cp[2] = t;
}
Ugly, but it works. You can put that code inline in a loop if your compiler won't automatically inline function calls for you, assuming CPU time is important. It's a bit harder to rearrange the byte order inside of a ByteBuffer object on the Java side.
- Robert JLv 75 years ago