problems reading binary file
Hi
I having trouble reading a binary file. The problem seems to occur
with reading some float values so I've made a small test file (from
SQL server using native file output) that contains just 5 floats.
-13.73482 , 20.689 , -99.99999 , 20.157 ,1 9.454
I read the file in and write out the values using
DataInputStream in = new DataInputStream(new
BufferedInputStream(new FileInputStream(filename)));
System.out.print(ByteSwapper.swap(in.readFloat())+" ");
System.out.print(ByteSwapper.swap(in.readFloat())+" ");
System.out.print(ByteSwapper.swap(in.readFloat())+" ");
System.out.print(ByteSwapper.swap(in.readFloat())+" ");
System.out.println(ByteSwapper.swap(in.readFloat())+" ");
The output is -13.734822 20.689 6.9055E-41 20.157 19.454
ie -99.99999 is now 6.9055E-41.
I'm trying to read in a much larger SQL outgest of mixed data types
integers, longs, doubles, floats and bytes and the only problem I've
spotted is floats of -99.9999 (which is a deafult value used for some
columns)
It was necessary to byte swap and ByteSwapper.swap(float) is something
I find on the web an dis below.
I tries other byte swap code with the same result.
Any ideas what I'm doing wrong with the 3rd value and presumably in
general.
Python code of
binaryFile = file('test.bin', 'rb')
while True:
rowBinary = binaryFile.read(20)
if not rowBinary:
break
print struct.unpack('<5f', rowBinary)
binaryFile.close()
correctly gives -13.734822273254395, 20.688999176025391,
-99.999992370605469, 20.156999588012695, 19.454000473022461
java(TM) 2 Runtime Environment, Standard Edition (build 1.5.0_12-b04
Thanks
Mike
public static float swap (float value)
{
int intValue = Float.floatToIntBits (value);
intValue = swap (intValue);
return Float.intBitsToFloat (intValue);
}
and
public static int swap (int value)
{
int b1 = (value >> 0) & 0xff;
int b2 = (value >> 8) & 0xff;
int b3 = (value >> 16) & 0xff;
int b4 = (value >> 24) & 0xff;
return b1 << 24 | b2 << 16 | b3 << 8 | b4 << 0;
}