1

I want to create a binary represenation of a floating-point number and be able to parse that number back when needed. By "binary representation" I do not mean "0.00101" but something like "101000101", that is to say, a sequesnce of 0's and 1's with no decimal separator. I need a way to both create such representation in String for a double and to parse a double of a String. Please do not mention the X Y problem because I do definitly need this method (something like "unsigned binary value").

Thank you in advance.

Convert Double to Binary representation? seemed to solve the problem with parsing double to String but I still need help with doing the opposite: from binary to double.

Community
  • 1
  • 1
OLEGSHA
  • 388
  • 3
  • 13

2 Answers2

5

To convert the bits of a double to a String, you can use Double.doubleToLongBits, which creates a long with the same bits as the double, followed by Long.toBinaryString to convert it to a String with the bits as characters.

double test = 0.5;
long doubleBits = Double.doubleToLongBits(test);
String doubleBitsStr = Long.toBinaryString(doubleBits);
System.out.println(doubleBitsStr);

Output: 11111111100000000000000000000000000000000000000000000000000000

To convert back, use Long.parseLong with a radix of 2 and Double.longBitsToDouble.

doubleBits = Long.parseLong(doubleBitsStr, 2);
test = Double.longBitsToDouble(doubleBits);
System.out.println(test);

Output: 0.5

To convert the bits of a float to a String, you can use Float.floatTointBits, which creates an int with the same bits as the float, followed by Integer.toBinaryString to convert it to a String with the bits as characters.

float test2 = 0.5f;
int intBits = Float.floatToIntBits(test2);
String intBitsStr = Integer.toBinaryString(intBits);
System.out.println(intBitsStr);

Output: 111111000000000000000000000000

To convert back, use Integer.parseInt with a radix of 2 and Float.intBitsToFloat.

intBits = Integer.parseInt(intBitsStr, 2);
test2 = Float.intBitsToFloat(intBits);
System.out.println(test2);

Output: 0.5

rgettman
  • 176,041
  • 30
  • 275
  • 357
0

Would Integer.toBinaryString(Float.floatToIntBits(yourNumber)); not work?

Neil Locketz
  • 4,228
  • 1
  • 23
  • 34