该列表摘自 thinking in java 第四版 23页:
基本数据类型 | 大小 | 最小值 | 最大值 | 包装器类型 |
boolean | - | - | - | Boolean |
char | 16-bit | Unicode 0 | Unicode 2^16 -1 | Character |
byte | 8-bit | -128 | +127 | Byte |
short | 16-bit | -2^15 | 2^15 -1 | Shoft |
int | 32bit | -2^31 | 2^31 -1 | Integer |
long | 64bit | -2^63 | 2^63 -1 | Long |
float | 32bit | IEEE754 | IEEE754 | Float |
double | 64bit | IEEE754 | IEEE754 | Double |
void | - | - | - | Void |
byte最大值
在java中有符号整数,首位数值0和1分别表示该数为正数和负数。以byte的最大值127为例打印二进制,代码为:
public static void main(String[] args) {
System.out.println("Integer.toBinaryString(127) : "+Integer.toBinaryString(127));
}
输出结果为:
Integer.toBinaryString(127) : 1111111
在java中byte的最大位数为8位(一个字节),为了包含该位数所能包含的数值并有正负之分故而保留了一位作为正负标识。所以正整数的最大值为127,用二进制表示为01111111。故而byte的正整数最大值为2的7次方减去1。
以下是将int值转换为二进制表示的方法,来至:IntegralToString( 由Integer.toBinaryString方法调用,该类被@hide)
public static String intToBinaryString(int i) {
int bufLen = 32; // Max number of binary digits in an int
char[] buf = new char[bufLen];
int cursor = bufLen;
do {
buf[--cursor] = DIGITS[i & 1];
} while ((i >>>= 1) != 0);
return new String(cursor, bufLen - cursor, buf);
}
int类型的为32位,输出值应为:0000000000000000000000001111111 。而上面的方法每次循环的判断条件为是向右位移且结果不等于0,导致其余位数没有进行输出。
补码
操作步骤为 先取反后加1
以int类型数值8为例,8的二进制为
00000000 00000000 00001000
首先取反
11111111 11111111 11110111
然后进行补码(+1,逢二进一),得到的值为
11111111 11111111 11111000
打印一下正负128的二进制:
Integer.toBinaryString(128) : 10000000
Integer.toBinaryString(-128) : 11111111111111111111111110000000
首先取反
11111111 11111111 11111111 011111111
然后进行补码
11111111 11111111 11111111 10000000
关于补码