如何将原始long值转换为byteValue,intValue,shortValue,hashCode,longValue。
import java.lang.*;
public class IntegerDemo {
public static void main(String[] args) {
Long l = 5148765430l;
int t = l.intValue();
System.out.println((new Integer(t)).byteValue());
System.out.println((new Integer(t)).doubleValue());
System.out.println((new Integer(t)).hashCode());
System.out.println((new Integer(t)).longValue());
System.out.println((new Integer(t)).shortValue());
System.out.println((new Integer(t)).intValue());
}
}
答案 0 :(得分:2)
long
占用64位,int
占32位。当您将long
转换为int
时,将放弃较高的32位,而较低的32位将保存为此int
。例如:
Long sourceLong = Long.MAX_VALUE; // in binary 0111 1111 1111 1111 1111 1111 1111 1111 1111 1111 1111 1111 1111 1111 1111 1111
int i = sourceLong.intValue(); // in binary 1111 1111 1111 1111 1111 1111 1111 1111
System.out.println(i); // decimal -1
Long copyLong = Long.valueOf(i);
System.out.println(sourceLong.equals(copyLong)); //false
因此,您无法将此int
转换回原点long
,因为较高的32位丢失了。
一个特例是当原始long
的高位33位全为零时,即使高位32位被放弃,它也不会失去任何准确度:
Long sourceLong = 1L; // in binary 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0001
int i = sourceLong.intValue(); // in binary 0000 0000 0000 0000 0000 0000 0000 0001
System.out.println(i); // decimal 1
Long copyLong = Long.valueOf(i);
System.out.println(sourceLong.equals(copyLong)); //true
将int
转换为short(16 bit)
,char(16 bit)
转换为byte(16 bit)
时,会发生类似的过程。