位运算符与逻辑运算符基本相似,不过后者的对象只是表示真和假的二值运算,位运算符的对象则是二进制数。Java语言中字节、字符和整数等都可以转换为二进制,所以位运算符的对象也可以是它们。常见位运算符有:
按位进行与运算 : &
按位进行或运算 : |
按位进行位异运算: ^
按位进行取反运算: ~
按位进行循环左移:<<,运算符左侧对象左移由右侧指定的位数,低位补0,最高位抛弃。带符号的左移位运算相当于对左操作数进行乘2运算。
按位进行循环右移:>>,运算符左侧对象右移由右侧指定的位数,若值为正,在最高位插入0,若值为负,在最高位插入1,即移入的最高位和原最高符号位相同。带符号的右移位运算相当于对左边的运算对象进行除2运算。
按位进行无符号右移:>>>,无论运算符左边的运算对象取值正负,都在高位插入0,即移入位始终补0.
要注意是没有按位进行无符号左移的。位运算符的操作数只能是整数,char,byte,short,
int和long,进行位运算时,总是先将字符型值、字节型值和短整型值转换为整型再进行位运算。位运算符游标的操作数用于指定移动的位数,按规定其不应超过左侧数的进制表示位数。
The bitwise operators allow you to manipulate individual bits in an integral primitive data type.Bitwise operators perform Boolean algebra on the corresponding bits in the two arguments to produce the result. The bitwise operators come from C’s low-level orientation, where you often manipulate hardware
directly and must set the bits in hardware registers. Java was originally designed to be embedded in TV set-top boxes, so this low-level orientation still made sense. However, you probably won’t use the bitwise operators much.
The bitwise AND operator (&) produces a one in the output bit if both input bits are one; otherwise, it produces a zero.
The bitwise OR operator (|) produces a one in the output bit if either input bit is a one and produces a zero only if both input bits are zero.
The bitwise EXCLUSIVE OR, or XOR (^), produces a one in the output bit if one or the other input bit is a one, but not both.
The bitwise NOT (~, also called the ones complement operator) is a unary operator; it takes only one argument. (All other bitwise operators are binary operators.) Bitwise NOT produces the opposite of the input bit—a one if the input bit is zero, a zero if the input bit is one.