复习 二进制位操作(bit operation),32bit integer 取值范围:-2^31 -- 2^31-1
0 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | = | 127 |
0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | = | 2 |
0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | = | 1 |
0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | = | 0 |
1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | = | −1 |
1 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | = | −2 |
1 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | = | −127 |
1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | = | −128 |
(2‘ compliment)二补数系统的最大优点是可以在加法或减法处理中,不需因为数字的正负而使用不同的计算方式。只要一种加法电路就可以处理各种有号数加法,而且减法可以用一个数加上另一个数的二补数来表示,因此只要有加法电路及二补数电路即可完成各种有号数加法及减法,在电路设计上相当方便。
Bitwise and Bit Shift Operators
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 operatio
代码:
public class Solution {
// you need treat n as an unsigned value
public int reverseBits(int n) {
int result = 0;
for(int i = 32; i > 0; i--){
result = result << 1;
result = result + (n & 1);
n = n >>> 1;
}
return result;
}
}