What will you learn from this passage?
Functions of ArrayBuffer Use of left and right displacement operations use of bitwise and operations
Of course, it’s not the wine that matters. Familiarity with binary bit operations during development will be the focus of this article.
1 Introduction to conversion tools
2 ArrayBuffer
First, when we initialize, we put the number 263 into an array, which is then converted to a stream of bytes into an ArrayBuffer.
In this case, we use the JS TypedArray to access the memory. MDN calls TypedArray Multiple views on the same data.
Looking at the code below, we use the Uint32Array to represent the “decimal display area”.
let target = new Uint32Array([263])Copy the code
let bytes = new Uint8Array(target.buffer)Copy the code
Target. buffer reads the byte stream stored in memory as an array of 8-bit unsigned bytes. The resulting bytes array is [7,1,0,0], and the corresponding binary array is [0000111,00000001, 00000000, 00000000].
Next we display the bytes array in the Binary display area.
Since there are 32 cells, we iterate from cell 0 to cell 31, each of which uses the getBit method to get the corresponding binary value from the Bytes array.
function writeBits() {
for (var i = 0; i < 32; I ++) {cell [I].textContent = getBit(I); }}Copy the code
function getBit(bit) {
return bytes[bit >> 3] & (0x1 << (bit & 0x7))?1 : 0;
}Copy the code
“Bit > > 3” group
“Yu bit & 7”
The ampersand and << operations
1 and 1 = 1
0 and 1 = 0
1 & 0 = 0
0, 0 = 0
That is, if we want to know whether n in the binary number “0100 0n01” is 0 or 1, we can do this:
0x01000n01 & 0x00000100Copy the code
0x1<< n positionCopy the code
example
The third step, make “valuer”, 0x1<<2, get 00000100.
Finally, the bytes[0]& evaluator determines whether the result is greater than or equal to 0, and the value of the second cell is obtained.
let res = 0x00000111 & 0x00000100 ? 1 : 0Copy the code
Res has a value of 1, which means the second cell has a value of 1. Isn’t it fun?
Review past