Programmatically find the size of the float

Disclaimer: This question may not be of practical value, it is more a matter of puzzle / curiosity.

In Java, I can write the following code to programmatically find the size of an int:

public static void main(String[] args) { int x = 1; int count = 1; while((x = x << 1) != 0) { count++; System.out.println("x: " + x + ", " + count); } System.out.println("size: " + count); } 

Is there a similar way to programmatically find the size of floating Java?

+6
source share
3 answers

write a float to ByteArrayOutputStream and get the length of the result.

 import java.io.*; class Test { public static void main(String[] args) throws Exception { ByteArrayOutputStream baos =new ByteArrayOutputStream(); DataOutputStream dos=new DataOutputStream(baos); dos.writeFloat(0f); System.err.println(baos.toByteArray().length); } } $ javac Test.java $ java Test 4 
+8
source

Java floats follow the IEEE floating point standard, so you can easily inform yourself about the details. In a nutshell, there is no clear separation between the “used” and “unused” parts of the float, as well as with two integer codes. The main division is in sign, mantissa and exponent. Perhaps you can see which mantissa bits are used and which exponent bits are used, but this is far from a trivial task.

+2
source

I would write a binary search. Start at 0, then go to plus or minus 0.5 * Float.MAX_VALUE and continue the iteration.

This method will work for any type of number - and should be much faster than your loop above.

+1
source

Source: https://habr.com/ru/post/920392/


All Articles