Home arrow static arrow Java Programming [Archive] - Converting float to binary
Warning: Creating default object from empty value in /www/htdocs/w008deb8/wiki/components/com_staticxt/staticxt.php on line 51
Java Programming [Archive] - Converting float to binary
This topic has 4 replies on 1 page.

Posts:57
Registered: 8/6/04
Converting float to binary  
Aug 6, 2004 9:42 AM



 
Hi,

I was wondering if anyone knew of a way to convert a float value (as ascii) to a binary value?

I need a program that will take in a number of floating values from a file, convert the values to binary and then write out these values in another file, 4 bytes at a time.

I know that you can convert decimals to binary with an easy function but i've searched for float to binary and came up with nothing.

any help would be really appreciated,

cheers!
 

Posts:1,183
Registered: 1/23/02
Re: Converting float to binary  
Aug 6, 2004 9:44 AM (reply 1 of 4)



 
[url http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Float.html#parseFloat(java.lang.String)]Float.parseFloat()[/url]
 

Posts:24,036
Registered: 2/3/03
Re: Converting float to binary  
Aug 6, 2004 9:50 AM (reply 2 of 4)



 
Integer.toBinaryString(Float.floatToRawIntBits(yourFloat));
 

Posts:3,055
Registered: 18/06/98
Re: Converting float to binary  
Aug 6, 2004 12:43 PM (reply 3 of 4)



 
One of the Java's problems is that you can easily get lost in the sea of Javadocs...

java.io.DataOutputStream

writeFloat(float v)
Converts the float argument to an int using the floatToIntBits method in class Float, and then writes that int value to the underlying output stream as a 4-byte quantity, high byte first.

java.io.DataInputStream

readFloat
public float readFloat()
throws IOException
Reads four input bytes and returns a float value. It does this by first constructing an int value in exactly the manner of the readInt method, then converting this int value to a float in exactly the manner of the method Float.intBitsToFloat. This method is suitable for reading bytes written by the writeFloat method of interface DataOutput.
 

Posts:27,518
Registered: 11/3/97
Re: Converting float to binary  
Aug 6, 2004 1:07 PM (reply 4 of 4)



 
You might want to verify exactly what the 4 bytes of output is.

If is is the same as floatToIntBits() then great. But if it is supposed to be read by some other application that expects something besides that specific layout then you are going to need to do something else.
 
This topic has 4 replies on 1 page.