我一直在玩转Integer到Float、Float到Long、Long到Int的转换,但当我遇到下面的情况时感到困惑。
当我将表示Long.MAX_VALUE的字符串s(63个1)转换时,我得到了一个NumberFormatException异常,这是预期的。因为Long是64位而Integer是32位,所以有31个额外的1(这是我的猜想,如果我错了,请纠正我)。
然而,我不确定为什么在将Long转换为Float时我没有得到NumberFormatException异常。Long再次是64位,而Float与Integer一样是32位。我知道比特在Float(IEEE 754浮点“单格式”位布局)中的解释方式不同,但所有其他31个额外的比特发生了什么?我真的很迷失......
此外,如何获得9.223372E18,即1011111000000000000000000000000比特字符串?那些0来自哪里?
public static void main(String[] args){
String s = String.valueOf(Long.MAX_VALUE);
print(s); //prints 9223372036854775807
print(Long.toBinaryString(Long.MAX_VALUE)); //prints 111111111111111111111111111111111111111111111111111111111111111
//Integer.valueOf(s) this throws NumberFormatException because Long is 64 bits and Integer is 32 so s is too large to be an Integer
print(Float.valueOf(s)); //prints 9.223372E18 Why no NumberFormatException? and how did it result 9.223372E18?
float f = Float.valueOf(s);
int intBits = Float.floatToIntBits(f);
print(Integer.toBinaryString(intBits)); //1011111000000000000000000000000 How come? s was a String of 1s now there are 0s?
}
public static <T> void print(T arg){
System.out.println(arg);
}