Article directory
Overview
Code example:
Bit operation, the value will be converted into binary for calculation, for example:
5 & 1 = "101 & 1 = "001
console.log(5 & 1)
//1
with &, or |
It is 1 only if it is the same as 1, and the others are 0.
Or the same 0 is 0, and the others are 1.
console.log(5 & 1)
//101 001
//001
//1
console.log(5 | 2)
//101 010
//111
//7
No
1 becomes 0, 0 becomes 1.
console.log(~1)
//-2
Why is the negation of 1 -2?
The sign bit 0 changes to 1, and the positive and negative are reversed, which is easy to understand.
The value is bitwise inverted, it should be 11111111111110.
Values are stored in complement.
A positive number is itself.
Negative numbers are bitwise negated plus one.
1111111110 is a negative number,
invert the bit and add one, which is 00000010, which
is 2.
XOR
1 if they are different, 0 if they are the same.
console.log(1 ^ 3)
//01 11
//10
//2
Zero padding left shift <<
Move all positions to the left without changing the sign.
The empty position is 0.
Discard the extruded part.
let a = 100
let b = a << 1
console.log(a, b)
console.log(a.toString(2))
console.log(b.toString(2))
Effect:
let a = -100
let b = a << 1
console.log(a, b)
console.log(a.toString(2))
console.log(b.toString(2))
Effect:
Positive and negative numbers have the same effect, they are all multiplied by two (unless they are too large and lost).
symbol fill right
Move all positions to the right.
The empty position is filled with the sign bit, positive numbers are filled with 0, and negative numbers are filled with 1.
Discard the extruded part.
let a = 100
let b = a >> 1
console.log(a, b)
console.log(a.toString(2))
console.log(b.toString(2))
Effect:
let a = -100
let b = a >> 1
console.log(a, b)
console.log(a.toString(2))
console.log(b.toString(2))
Effect:
Positive and negative numbers have the same effect, they are divided by two.
zero padding right shift
Move all positions to the right, and the symbols move with them.
The empty position is 0.
Discard the extruded part.
No explanation.