The numbers, strings, pictures, audio and video used in our code are finally converted to binary storage, while the data transmitted by audio and video stream is directly binary, which is a necessary knowledge point.

  • Note: upper right belt*Content is the key/difficult point, may need more time to learn and digest

One, base conversion

It is said that human beings have ten fingers so they use the decimal notation to represent numbers.

Specifies how to represent each base number:

  • D represents Decimal, Decimal, such as 29D
  • B stands for Binary, such as 11.011b
  • O stands for Octal, Octal, as in 1727O
  • X stands for Hex, as in AD19FX

Turn the decimal

Converting other bases to decimal follows the same conversion rule for each bit:

value * N^M

  • N – indicates the base system, for example, 2 in binary system and 10 in decimal system
  • M – Decimal points to the left are 0, 1, 2, 3, 4, 5… And the decimal point to the right is -1-2-3-4-5…
  • Value – indicates a value in the range [0, n-1]
// 11010011B => ? D
  1*2^7 + 1*2^6 + 0*2^5 + 1*2^4 + 0*2^3 + 0*2^2 + 1*2^1 + 1*2^0
= 1*128 + 1*64 + 0*32 + 1*16 + 0*8 + 0*4 + 1*2 + 1*1 
= 211D

// 7135O => ? D
  7*8^3 + 1*8^2 + 3*8^1 + 5*8^0
= 7*512 + 1*64 + 3*8 + 5
= 3677D

// 7FAX => ? D
  7*16^2 + 15*16^1 + 10*16^0
= 7*256 + 15*16 + 10
= 2042D

Copy the code

Decimal to binary

An integer bit

Keep dividing by 2 until it doesn’t divide.

376D conversion process divided by2remainder2 | 376
2 | 188
2 |  94
2 |  47  
2 |  23.1
2 |  11.1
2 |   5.1
2 |   2.1
2 |   1
      0.1The completion remainder is0, the remainder below is high, 101111000D from bottom to top, and the binary conversion is completedCopy the code

Decimal places

Multiply by 2, carry by 1, carry by 0, cancel by decimals, or go on forever (usually by finding loops)

0.275D conversion process marker0.275
* 2
    0.55    0
* 2  
    0.1	    1 <- 0.1The dot is followed by *2     
    0.2	    0 <- 0.2The dot is followed by *2     
    0.4     0* left *2     
    0.8	    0
* 2     
    0.6     1
* 2     
    0.2     1
* 2     
    0.4     0* write0011Start the loop2     
    0.8     0
* 2     
    0.6     1
* 2     
    0.2     1

// (0011) indicates a loopThe top is marked high, turning0.010(0011)B

Copy the code

JS base conversion API

Turn the decimal

parseInt(string, [radix])

  • Radix – conversion of the base number, along to avoid errors
// Use the API to verify the correctness of the previous manual conversion
parseInt('7FA'.16) / / 2042

parseInt('7135'.8) / / 3677

parseInt('11010011'.2) / / 211

Copy the code

Transfer from decimal to other bases

numObj.toString([radix])

Number(376..toString(2)) // 101111000B
Copy the code

Second, JS numerical storage

The decimal point

The representation of the value can be divided into fixed point number and floating point number according to whether the decimal point is fixed or not

  • Fixed-point number

    • Fixed integer – The decimal point is fixed to the far right and does not occupy space
    • Fixed decimal point – The decimal point is fixed on the most important side, no space
  • Floating point Numbers

    • The decimal point is not fixed, can float left and right, almost all computer languages use floating point IEEE754 standard

IEEE754

IEEE754 is a binary floating-point arithmetic standard, and JS uses the double precision of this standard to store the Number type, that is, 64-bit storage. Look at what the elevation says:

The Number type uses IEEE754 format to represent integer and floating point values (also called double values in some languages).

IEEE754 indicates that data is in the following format:

  sign   exponent      mantissa/fraction
+------+---------+---------------------------+
|  1   | 2 ~ 12  |        13 ~ 64| + -- -- -- -- -- - + + -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- + altogether1A | altogether11A | altogether52Copy the code
  • The sign bit (sign), the highest bit, 0/1 indicates positive/negative
  • It has the highest exponent from 2 to 12
  • Mantissa /fraction, the remainder. Using scientific notation, the highest bit is 1, so this bit is not explicitly represented, so it can actually represent 53 bits. (Note: 0D is a special value)

To name two 🌰 :

// Can be cut to two, JS value storage -> the code area of the decimal point, 0.1 and 0.2 mark reference conversion process

0.1D
= 0.00011(0011)B
= 2^ -4 * 1.1(0011 repeat 12 times)0011B       // 1
= 2^ -4 * 1.1(0011 repeat 12 times)010B        // add a bunch of zerosWrite write1 + 4*12 + 3 = 520.2D 
= 0.(0011)B
= 2^ -3 * 1.1(0011 repeat 12 times)0011B       // 1
= 2^ -3 * 1.1(0011 repeat 12 times)010B        // add a bunch of zerosWrite write1 + 4*12 + 3 = 52Copy the code

0.1 + 0.2! = = 0.3 *

Take the top result

0.1D + 0.2D
= 2^ -3 * 0.11(0011 repeat 12 times)01B  // Index bit calibration
+ 2^ -3 * 1.1(0011 repeat 12 times)010B
= 2^ -3 * 0.1100110011001100110011001100110011001100110011001101B
+ 2^ -3 * 1.1001100110011001100110011001100110011001100110011010B
= 2^ -3 * 10.0110011001100110011001100110011001100110011001100111B  // Convert to IEEE754
= 2^ -2 * 1.0011001100110011001100110011001100110011001100110100B
0.3D = 0.010011001100110011001100110011001100110011001100110011B   // 0.3d binary can be obtained by referring to the previous code area, or by using short division yourselfWrite write writeCopy the code

Three, binary addition and subtraction operations

add

Addition does not explain much, that is, the number of digits add up, every 2 into 1.

subtraction

Subtraction is the focus, the final binary subtraction is the use of complement, the following simple expression from 2-1 to evolve.

The original code

The source code uses the highest bit 0/1 to indicate positive/negative values.

Try adding

    2 - 1 = 1= >0 010 + 1 001 = 1 011= > -3! = =1
Copy the code

Obviously using source code addition to indicate subtraction does not work because the sign bit affects the positive and negative values but does not participate in the operation

Inverse and complement *

The purpose of the existence of inverse code is to quickly obtain the complement. The following analysis:

  • The formula for converting negative source code to complement is 2^(n+1) + value, where n is the highest bit and value is the source code.
  • And if we were to find the complement according to this formula would be troublesome, so we introduced the inverse code, the inverse code formula is 2^(n+1) -1 + value. And by summing up: the inverse of the negative original code is to take the inverse according to the bit, and then according to the formula obviously complement = inverse + 1, so get the method of taking the negative complement quickly.

In the complement, the positive number remains the same, and the negative number is inverted except for the sign bit and added by 1.

    2 - 1 = 1= >0 0010 + 1 0001
    0 0010 + 1 1110  // a positive complement is itself, and a negative number divided by a sign bit
    0 0010 + 1 1111  // add 1 to get the negative complement
  = 0 00001 = 1*2^0 = 1

Copy the code

No matter how many bits are represented, the sign bit goes to the highest bit.

Four, JS bit operation

All values in ECMAScript are stored in IEEE 754 64-bit format, but bitwise operations do not apply directly to 64-bit representations. Instead, values are converted to 32-bit integers, then bitwise operations are performed, and then the result is converted to 64-bit.

AND

The and operator/operator – &, and, and the truth table and examples are as follows:

/ / click with
/ / 0 to 1
// +-----+-----+
/ / | | 0 0 0 |
// +-----+-----+
/ / 1 1 | | | 0
// +-----+-----+

2 & 10
=   00010B 
  & 01010B
------------
    00010B
=   2D

Copy the code

OR

Or operator/operator – |, take or counterpoint, truth table and an example is as follows:

/ / or by location
/ / 0 to 1
// +-----+-----+
/ / | 0 0 1 | |
// +-----+-----+
/ / | | 1 | 1
// +-----+-----+

2 | 10
=   00010B 
  & 01010B
------------
    01010B
=   10D

Copy the code

NOT *

Non-operator/operator – ~.

Positive number: take the inverse by bit, find the complement code

Negative number: complement, inverse by bit

Examples are as follows:

/ / not by location
/ / 0 to 1
// +-----+-----+
/ / | 1 | | 0
// +-----+-----+

~ 10
= ~ 00000000000000000000000000001010B 
=   11111111111111111111111111110101B  / / the not
=   10000000000000000000000000001011B  / / for complement
=   -11

~ -10
= ~ 10000000000000000000000000001010B 
=   11111111111111111111111111110110B  / / for complement
=   00000000000000000000000000001001B  / / the not
=   9

Copy the code

The trick for bitwise non-quick evaluation is to invert the value and subtract 1

XOR

The xor operator/operator – ^, and the xor of the bit (can be considered as xor, the value on the bit is true, otherwise false), the truth table and examples are as follows:

// Bitwise xOR
/ / 0 to 1
// +-----+-----+
/ / | 0 0 1 | |
// +-----+-----+
/ / | 1 | | 0
// +-----+-----+

2 ^ 10
=   00010B 
  ^ 01010B
------------
    01000B
=   8D

Copy the code

Left shift

Left shift operator/operator – <<, sign bit unchanged, all bits moved to the left how many bits, void fill zero, example:

49 << 6= 00000000000000000000000000110001 b write write write write write write < < 00000000000000000000110001000000 b write write write write write write = d - 313611 << 2= 10000000000000000000000000001011 b write write write write < < 10000000000000000000000000101100 b write write write write = -44 

Copy the code

Right shift *

Operator/operator – >>, the symbol bit remains unchanged, how many bits to move to the right of all bits, the value of the empty complement symbol bit, for example:

49 >> 6= 00000000000000000000000000110001 b write write write write write write > > 00000000000000000000000000000000 b write write write write write write = 0 d -11 >> 2
=    10000000000000000000000000001011B 
=    11111111111111111111111111110101B   / / for complementWrite write write write > > 11111111111111111111111111111101 b// add +1Write write write write = = b - 100000000000000000000000000000113

Copy the code

Unsigned right shift

Unsigned right shift operator/operator – >>>, how many bits to move to the right, void fill zero, as shown in the following example:

// Positive >>> is the same as >>>

-11 >>> 2
=    10000000000000000000000000001011B 
=    11111111111111111111111111110101B   / / for complement
   ->
 >>> 00111111111111111111111111111101B                                      
     ->
=    10000000000000000000000000000011B
=    1073741821

Copy the code

Five, add large numbers

Finite memory is bound to encounter the problem of large number calculation, let us through an example to learn how to deal with large number adding skills:

// Convert the numeric type into an array that stores each digit, using vertical calculation: reverse the array, add the digits, and fill the decimal one
// Note:
// 1. Update the carry
// 2. Check if the highest bit is zero

function string2array(s){
  return String(s).split(' ').reverse().map(val= > parseInt(val))
}

function bigAdd(s1, s2){
  const list1 = string2array(s1)
  const list2 = string2array(s2) 
  let length
  const sum = Array.from(Array(length = Math.max(list1.length + 1, list2.length + 1)), _= > 0)
  let up = 0
  for (let i = 0; i < length + 1; i++) {
    list1[i] ?? (list1[i] = 0)
    list2[i] ?? (list2[i] = 0)
    sum[i] = list1[i]  + list2[i] + up
    up = sum[i] > 9 ? 1 : 0
    sum[i] = sum[i] % 10
  }
  sum[sum.length - 1= = =0 && sum.pop()
  return sum.reverse().join(' ')}// test case
bigAdd('1234567890343'.'123434256567890')


Copy the code

For more large number problems, please refer to this article for further study.

Six, summarized

  • Complement is to solve the subtraction, there are negative numbers are inseparable from the application of complement
  • Regarding the use of bit operations, my opinion is that business code should be used sparingly, after all, for readability
  • The bitwise section uses 32-bit examples based on elevation, and it was mentioned earlier that bitwise performance would be worse for this reason (actually not by much). The ES5 specification does go to 32-bit first, but this is not the case in the latest ES2021 specification. A word of caution about the new elevation: there are references to ES3, such as the use of variable Objects in the Execution Context, and there will be an opportunity to write a later article on function execution.

Write here binary expression, storage, operation I believe we have some understanding, skilled use also depends on hands-on coding, and this article can only take you to have a preliminary understanding of binary, if you want to more in-depth class refer to the following links to learn.

Reference and expand reading

Revealed 0.1 + 0.2! = 0.3

Why 0.1 + 0.2 === 0.30000000000000004: Implementing IEEE754 in JS

complement

Get behind 0.1 + 0.2 === 0.30000000000000004

Rules for multiplication and division implemented by computers

How does a computer know how to add, subtract, multiply and divide

Principles of Computer composition —-2.5 Introduction to multiplication and division

JavaScript floating point puzzle: why isn’t 0.1 + 0.2 equal to 0.3?