Notes: Primitives Storage and Operator

来源:互联网 发布:excel数据交换 编辑:程序博客网 时间:2024/06/12 21:16

There is something special about the storage realization of Java's number. 


Java uses the complement of positive number to store the negative number. For example, we use Integer class (int) to illustrate. In Java, Integers have 32 bits. The first bit is to show that this is a positive or negative number. If it is 0, it is positive. In contrast, 1 means that this is a negative number. 


If the integer is a positive number, the rest bits of that integer will be exactly the binary number for the value of that integer. However, if the integer is a negative number, Java will use the complement binary version of that integer. 


所有的整数类型(除了char 类型之外)都是有符号的整数。这意味着他们既能表示正数,又能表示负数。 Java使用补码来表示二进制数 ,在补码 表示中 ,最高位为符号位 ,正数的 符号位 为 0,负数为 1。补 码 的 规 定 如 下 : 


对 正 数 来 说 ,最高 位 为 0,其余 各 位 代 表 数 值 本 身 (以二 进制 表 示 ),如 +42的补码 为 00101010。 


对 负 数 而 言 ,把该 数 绝 对 值 的 补 码 按 位 取 反 ,然后 对 整 个数 加 1,即得 该 数的 补 码 。 如 -42的补 码 为 11010110 (00101010 按 位 取 反 11010101 +1=11010110 ) 


Java 位运算符 


Java 定义的位运算(bitwise operators )直接对整数类型的位进行操作,这些整数类型包括long,int,short,char,and byte 。表4-2 列出了位运算: 


运算符 
结果 



按位非(NOT)(一元运算) 



按位与(AND) 



按位或(OR) 



按位异或(XOR) 


>> 
右移 


>>> 
右移,左边空出的位以0填充 ;无符号右移 


<< 
左移 


&= 
按位与赋值 


|= 
按位或赋值 


^= 
按位异或赋值 


>>= 
右移赋值 


>>>= 
右移赋值,左边空出的位以0填充 ;无符号左移 


<<= 
左移赋值 

0 0