Java 编码和解码字节值、intValue、shortValue、hashCode、longValue
在将原始long值转换为byteValue、intValue、shortValue、hashCode、longValue之后,如何打印回原始long值Java 编码和解码字节值、intValue、shortValue、hashCode、longValue,java,int,byte,decode,encode,Java,Int,Byte,Decode,Encode,在将原始long值转换为byteValue、intValue、shortValue、hashCode、longValue之后,如何打印回原始long值 import java.lang.*; public class IntegerDemo { public static void main(String[] args) { Long l = 5148765430l; int t = l.intValue(); System.out.p
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());
}
}
long
占用64位,int
占用32位。将long
转换为int
时,较高的32位将被放弃,而较低的32位将保存为thisint
。例如:
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
的higer 33位全部为零时,即使放弃higer 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位)
,转换为char(16位)
,转换为byte(16位)Along
占用64位,int
占用32位时,也会发生类似的过程。将long
转换为int
时,较高的32位将被放弃,而较低的32位将保存为thisint
。例如:
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
的higer 33位全部为零时,即使放弃higer 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位)
,转换为char(16位)
,转换为byte(16位)
,则会发生类似的过程,您不能这样做。当您将值转换为int
时,您丢弃了32位值。您不能。将值转换为int
时,您丢弃了32位值。