Java: How to convert a String of Binary values to a Float and vice-versa?

前端 未结 4 1657
情书的邮戳
情书的邮戳 2020-12-18 06:22

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

4条回答
  •  臣服心动
    2020-12-18 07:13

    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);
    

提交回复
热议问题