How to get the bits of a float value in Java

1 Answer

0 votes
import java.nio.ByteBuffer;

public class Program {
    public static void main(String[] args) {
        float value = 3.14f;
        byte[] bytes = ByteBuffer.allocate(4).putFloat(value).array();

        StringBuilder binaryString = new StringBuilder("0b");
        
        for (byte b : bytes) {
            binaryString.append(String.format("%8s", Integer.toBinaryString(b & 0xFF)).replace(' ', '0')).append("_");
        }
        
        binaryString.deleteCharAt(binaryString.length() - 1);

        System.out.println(binaryString.toString());
    }
}

// https://www.h-schmidt.net/FloatConverter/IEEE754.html



/*
run:

0b01000000_01001000_11110101_11000011

*/

 



answered May 22, 2024 by avibootz

Related questions

2 answers 208 views
208 views asked May 22, 2024 by avibootz
1 answer 109 views
1 answer 96 views
96 views asked Sep 3, 2023 by avibootz
1 answer 145 views
4 answers 331 views
331 views asked Nov 8, 2016 by avibootz
1 answer 192 views
...