R
RC
This is continuation for my August 24th posted
"How to convert int/float etc into byte[]?"
float f = -10.2;
Here is a C/C++
// write 1 byte of float to the file pointer
fwrite((char *)f, sizeof(float), 1, fp);
In Java, if I used DataOutputStream class
dataOutputStream.writeFloat(f);
But when I compared the content of two
binary files (C/C++ and Java) by command
"od -a binFile"
or
"od -c binFile"
The output binary file written by Java is
different from the one written by C/C++
Then I tried different way:
byte[] byteArrays = (Float.toString(f)).getBytes();
dataOutputStream.write(byteArrays, 0, byteArray.length);
This time the binary becomes ASCII as "-10.2"
Then, I tried one more way:
byte[] byteArray = new byte[1];
byte b = (Float.valueOf(f)).byteValue();
byteArray[0] = b;
dataOutputStream.write(byteArrays, 0, byteArray.length);
But still no luck, the output binary file in Java
is still not the same as one in C/C++.
So back to my original question, what is the correct
way to convert a float, int, double, short, long, etc.
into a byte array?
Thank Q very much!
"How to convert int/float etc into byte[]?"
float f = -10.2;
Here is a C/C++
// write 1 byte of float to the file pointer
fwrite((char *)f, sizeof(float), 1, fp);
In Java, if I used DataOutputStream class
dataOutputStream.writeFloat(f);
But when I compared the content of two
binary files (C/C++ and Java) by command
"od -a binFile"
or
"od -c binFile"
The output binary file written by Java is
different from the one written by C/C++
Then I tried different way:
byte[] byteArrays = (Float.toString(f)).getBytes();
dataOutputStream.write(byteArrays, 0, byteArray.length);
This time the binary becomes ASCII as "-10.2"
Then, I tried one more way:
byte[] byteArray = new byte[1];
byte b = (Float.valueOf(f)).byteValue();
byteArray[0] = b;
dataOutputStream.write(byteArrays, 0, byteArray.length);
But still no luck, the output binary file in Java
is still not the same as one in C/C++.
So back to my original question, what is the correct
way to convert a float, int, double, short, long, etc.
into a byte array?
Thank Q very much!