Java位移运算符

Java中的位移操作符就3个,而且仅对整数类型有效,分别为

  • << 左移,右空位补0,相当于乘2
  • >> 右移(带符号),左空位补符号位(负数补1,正数补0),相当于除2
  • >>> 右移(无符号),左空位补0

对于32位的int类型,位移超过31时(对于64位的long类型,位移超过63时),编辑工具(intelliJ)会显示warm提示(负数和超范围的数逗被认为是开发者coding错误),但仍可运行。结果等同于 当前位移数%类型长度(整形32,长整型long 64)

对于位移负数位x,等效于将x+n*类型长度,即将负数位移数转换成小于类型长度的正整数,然后再做位移操作。

看一波Oracle的原文介绍

The Java programming language also provides operators that perform bitwise and bit shift operations on integral types. 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”. For example, a byte contains 8 bits; applying this operator to a value whose bit pattern is “00000000” would change its pattern to “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.

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.

1
2
3
4
5
6
7
8
9
> class BitDemo {
> public static void main(String[] args) {
> int bitmask = 0x000F;
> int val = 0x2222;
> // prints "2"
> System.out.println(val & bitmask);
> }
> }
>

参考

Bitwise and Bit Shift Operators

Java中的移位运算符

坚持原创技术分享,您的支持是对我最大的鼓励!