编码和解码 byteValue、intValue、shortValue、hashCode、longValue

Encoding and decoding byteValue, intValue, shortValue, hashCode, longValue

如何在将 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.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位将被保存为这个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)

时,会发生类似的过程