Documentation

The Java™ Tutorials
Hide TOC
Bitwise and Bit Shift Operators按位运算符和位移位运算符
Trail: Learning the Java Language
Lesson: Language Basics
Section: Operators

Bitwise and Bit Shift Operators按位和位移位运算符

The Java programming language also provides operators that perform bitwise and bit shift operations on integral types.Java编程语言还提供了对整数类型执行按位和位移位操作的运算符。The operators discussed in this section are less commonly used.本节中讨论的运算符不太常用。Therefore, their coverage is brief; the intent is to simply make you aware that these operators exist.因此,他们的报道是简短的;其目的只是让您意识到这些操作符的存在。

The unary bitwise complement operator "~" inverts a bit pattern; it can be applied to any of the integral types, making every "0" a "1" and every "1" a "0".一元逐位补码运算符“~”反转位模式;它可以应用于任何整数类型,使每个“0”都成为“1”,每个“1”都成为“0”。For example, a byte contains 8 bits; applying this operator to a value whose bit pattern is "00000000" would change its pattern to "11111111".例如,一个byte包含8位;将此运算符应用于位模式为“00000000”的值会将其模式更改为“11111111”。

The signed left shift operator "<<" shifts a bit pattern to the left, and the signed right shift operator ">>" shifts a bit pattern to the right.带符号的左移位运算符“<<”将位模式向左移位,而带符号的右移位运算符“>>”将位模式向右移动。The bit pattern is given by the left-hand operand, and the number of positions to shift by the right-hand operand.位模式由左侧操作数给出,位置数由右侧操作数移位。The unsigned right shift operator ">>>" shifts a zero into the leftmost position, while the leftmost position after ">>" depends on sign extension.无符号右移运算符“>>>”将零移到最左边的位置,而将最左边的位置移到“>>”取决于符号扩展。

The bitwise & operator performs a bitwise AND operation.按位&运算符执行按位AND运算。

The bitwise ^ operator performs a bitwise exclusive OR operation.按位^运算符执行按位异或运算。

The bitwise | operator performs a bitwise inclusive OR operation.按位|运算符执行按位包含或运算。

The following program, BitDemo, uses the bitwise AND operator to print the number "2" to standard output.以下程序BitDemo使用按位AND运算符将数字“2”打印到标准输出。

class BitDemo {
    public static void main(String[] args) {
        int bitmask = 0x000F;
        int val = 0x2222;
        // prints "2"
        System.out.println(val & bitmask);
    }
}

Previous page: Equality, Relational, and Conditional Operators
Next page: Summary of Operators