Review bits operation (bit operation), 32bit integer value range: -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 |
The biggest advantage of the (2 ' compliment) Two complement system is that it can be used in addition or subtraction, without having to use a different calculation method because of the positive or negative numbers. As long as an addition circuit can deal with a variety of number addition, and subtraction can be represented by one count plus another number of two complement, so as long as there are addition circuit and two complement circuit can complete a variety of number addition and subtraction, in the circuit design is quite convenient.
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 is less commonly used. Therefore, their coverage is brief; The intent is to simply make your aware that these operators exist.
The unary bitwise complement operator " ~
" inverts a bit pattern; it can be applied to any of the integral types, makin G every "0" a "1" and every "1" a "0". For example, a byte
contains 8 bits; Applying the operator to a value whose bit pattern was "00000000" would change it PA Ttern to "11111111".
The signed left shift operator " <<
" shifts a bit pattern to the left, and the signed right shift operator " >>
" shift s 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 to 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
Code:
public class Solution {
You need treat n as an unsigned value
public int reversebits (int n) {
int result = 0;
for (int i = +; i > 0; i--) {
result = result << 1;
result = result + (n & 1);
n = n >>> 1;
}
return result;
}
}
Jan 08-reverse Bits; Binary; Integer; Bits; Review bit arithmetic and binary expression