What do you learn from this article?
The use of xor operators
The use of or operatorsThe use of an inverse operator with an operator
Binary operations (1)- Develop a base conversion tool
The last article focused on reading data from an ArrayBuffer memory, which means reading the binary values of each cell from an array of Bytes.
1. Realization of toggle function
function toggleBit(bit) {
bytes[bit >> 3] = bytes[bit >> 3^ (0x1 << (bit & 0x7));
writeBits();
}Copy the code
Xor operation
1 ^ 1 = 0
0 ^ 1 = 1
1 ^ 0 = 1
0 ^ 0 = 0
The xOR rule is not easy to remember, but just remember the phrase “addition does not carry” and everything will fall into place.
In binary, the result of 1 + 1 is 10. And if you don’t add, 1 + 1 = (1), 0 = 0, take the 1 out of the carry, so 1 to the 1 is going to be 0.
Then the xOR effect can be used to reverse the value of position N to achieve the toggle function.
0x00000n00 ^ 0x00000100Copy the code
We start by making a “negator” using the left shift operation, which is 0x00000100.
0x1 << 2(position of n)Copy the code
If n is 1,0 x00000100^0x00000100 you get 0x00000000,
If n is 0,0 x00000000^0x00000100 is 0x00000100;
You can always invert position n.
2. Implementation of set function
We bind setBit events to the 1 and 0 keys on the keyboard.
function setBit(bit, value) {
if (value === 1) {
bytes[bit >> 3] = bytes[bit >> 3] | (0x1 << (bit & 0x7));
} else if(value === 0) {
bytes[bit >> 3] = bytes[bit >> 3& ~ (0x1 << (bit & 0x7));
}
writeBits();
}Copy the code
“| bitwise or” operations
1 | = 1
0 | = 1
1 | 0 = 1
0 | 0 = 0
Let’s say we want to set position n to 1.
0x00000n00 | 0x00000100Copy the code
As usual we make a “setter” with the left shift operation, which is 0x00000100.
0x1 << 2(position of n)Copy the code
If n is 1, 0 x00000100 | 0 x00000100 got is 0 x00000100,
If n is 0, 0 x00000000 | 0 x00000100 get or 0 x00000100;
You can always set position N to 1.
Now let’s talk about setting the cell to 0.
“Bitwise and” and “inverse”
1 and 1 = 1
0 and 1 = 0
1 & 0 = 0
0, 0 = 0
Last time we used and for get, but now we’re going to set position n to 0.
0x00000n00 & ~0x00000100Copy the code
As usual, we make a “zero” with the left displacement operation, that is, we get 0x00000100 first. Then invert 0x00000100 to get 0x11111011.
~ (0x1 << 2(position of n)Copy the code
If n is 1,0 x00000100&0x11111011 is 0x00000000,
If n is 0, 0 x00000000 & | 0 0 x11111011 get or 0 x00000000;
You can always set position n to 0.
3 summary
Review past
Shorthand CARDS
When n is a binary number,
And operations 0x00000n00&0x00000100 read the value of n;The xOR operation 0x00000n00 ^ 0x00000100 negates n;Or operation 0 x00000n00 | 0 x00000100 set n to 1;0x00000n00&0x00000100 set n to 0.