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

时间:2018-05-01 04:22:20

标签: java int byte decode encode

如何将原始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());
  }
}

1 个答案:

答案 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)时,会发生类似的过程。