5
votes

How do I convert the float value of 12345.12346f to a String of binary values, i.e. "0011010101010101", and vice-versa?

4
do you want the representation of this float in memory ? Because float doesn't really have a binary representation, int sure have, but float not. - krtek
Do you just want any reversible conversion, or a sensible (or maybe readable) one? - PaĆ­lo Ebermann

4 Answers

15
votes

I'm not sure it is what you want, but here's a solution to have the binary representation of the IEEE 754 floating-point "double format" bit layout for a float (it is basically the memory representation of a float) :

int intBits = Float.floatToIntBits(yourFloat); 
String binary = Integer.toBinaryString(intBits);

For the reverse procedure :

int intBits = Integer.parseInt(myString, 2);
float myFloat = Float.intBitsToFloat(intBits);
3
votes

Working sample:

class F { 
  public static void main( String ... args ) { 
    System.out.println(
          Integer.toBinaryString( 
             Float.floatToIntBits(12345.12346f)
          ) 
     );
  }
}

Output:

1000110010000001110010001111110
3
votes

For signed Floats, use Long or BigInteger to parse the string. Casting by int causes the digit at first of 32 bits be intepreted as sign digit. procedure :

int intBits = Float.floatToIntBits(yourFloat); 
String binary = Integer.toBinaryString(intBits);

reverse procedure :

int intBits = new BigInteger(myString, 2).intValue();
// int intBits = (int) Long.parseLong(myString, 2);
float myFloat = Float.intBitsToFloat(intBits);
0
votes

You can get the bit representation of a Java Float value using

Float.floatToIntBits(float f);

Once you have done that you can test each bit of the resulting int in turn, starting with the highest, and find out if it set, writing a '1' if it is set and a '0' if not.