Java的int随处可见的是永远都是32位有符号整数吗?
Answers:
是的,它在Java语言规范中定义。
积分类型是
byte,short,int,和long其值是8位,16位,32位和64位带符号的二进制补码整数,分别和char,其值是16位无符号整数表示UTF-16码单位(第3.1节)。
以及来自第4.2.1节:整数类型和值:
整数类型的值是以下范围内的整数:
- 对于字节,从-128到127(含)
- 简而言之,从-32768到32767(含)
- 对于int,范围为-2147483648至2147483647(含)
- 长期而言,从-9223372036854775808到9223372036854775807(含)
- 对于char,从'\ u0000'到'\ uffff'(含),即从0到65535
Java 8增加了对无符号整数的支持,原语int仍然是有符号的,但是有些方法会将它们解释为无符号的。
以下方法已添加到Java 8的Integer类中:
这是一个示例用法:
public static void main(String[] args) {
int uint = Integer.parseUnsignedInt("4294967295");
System.out.println(uint); // -1
System.out.println(Integer.toUnsignedString(uint)); // 4294967295
}
作为补充,如果64位长不能满足您的要求,请尝试java.math.BigInteger。
它适用于数字超出64位长范围的情况。
public static void main(String args[]){
String max_long = "9223372036854775807";
String min_long = "-9223372036854775808";
BigInteger b1 = new BigInteger(max_long);
BigInteger b2 = new BigInteger(min_long);
BigInteger sum = b1.add(b1);
BigInteger difference = b2.subtract(b1);
BigInteger product = b1.multiply(b2);
BigInteger quotient = b1.divide(b1);
System.out.println("The sum is: " + sum);
System.out.println("The difference is: " + difference);
System.out.println("The product is: " + product);
System.out.println("The quotient is: " + quotient);
}
输出为:
总和是:18446744073709551614
区别是:-18446744073709551615
产品是:-85070591730234615856620279821087277056
商为:1
public static final int SIZE = 32;从Java 1.5开始就指定了该常数。