Bit computing and in-depth study of the use of js

What is bit computing?

Bit operation in the digital bottom (i.e., indicates a 32-digit number) for computing. Since the lower bit operation is an arithmetic operation, it is often the fastest speed (relative to other operations such as addition, subtraction, it), and by means of positioning calculation sometimes we can achieve a simpler program logic, the disadvantage is very intuitive, many applications can not be used.

Bit integer arithmetic only works, if a child is not an integer arithmetic, it will automatically be converted to an integer and then run. Although within the JavaScript, values ​​are stored as 64-bit floating point number, but doing bit operation time, based on 32-bit signed integer operation is performed, and also returns a 32-bit integer with a sign value.

About Binary

The following == == from w3shool:
the ECMAScript integer of two types, i.e., a signed integer (allows positive and negative), and unsigned integer (positive numbers only). In ECMAScript, all default integer literals are signed integers, what does this mean?

Using a signed integer value of 31 represents an integer, unsigned integer represented by the first 32-bit, 0 for positive, 1 for negative. To a numerical range -2147483648 2147483647.

It can be stored in two different forms of embodiment of a signed binary integer, for storing a positive number, for storing negative numbers. A positive number stored in binary form is true, the first 31 bits each bit represents a power of 2, the first bit (bit 0) begins, represent 20, 2 (position 1) 21. Unused filled with 0 bits, i.e., ignored. For example, the picture shows a representation of the number 18.
image

== above from w3shool ==:

That binary and decimal in the js how to change it? as follows

// 十进制 => 二进制
let num = 10;
console.log(num.toString(2));
// 二进制 => 十进制
let num1 = 1001;
console.log(parseInt(num1, 2)); 

What are the js-bit computing?

  • Bitwise OR |

    For each pair of bit operation is performed (AND). Only a and b is an arbitrary 1, a | b is 1. The following table 9 | 3 = 11

9 = 1 0 0 1
3 = 0 0 1 1
11 = 1 0 1 1

Scenario:

  1. ToSei

    For general integer, the return value will not have any change. For an integer power of 2 greater than 32, greater than 32 digits will be discarded.

function toInt(num) {
    return num | 0
}
console.log(toInt(1.8))        // 1
console.log(toInt(1.23232))    // 1
  1. Boundary judgment
    If we have a drag event, the provisions of the dragged module requires internal motion in a container, then there is a boundary judgment, which also includes up, down, left and right four kinds of single boundary, as well as similar on the right, superposition of the left boundary, if we need to record this state, if the judge bit operation to use than simpler, lower right, respectively left boundary 1,2,4,8 represent four kinds, as follows:
let flag = 0;
if (pos.left < left) flag = flag | 8;
if (pos.right > right) flag = flag | 2;
if (pos.bottom > bottom) flag = flag | 4;
if (pos.top < top) flag = flag | 1;
switch(flag) {
    // 上
    case 1: 
    // 右
    case 2:
    // 右上
    case 3:
    // 下
    case 4:
    // 右下
    case 6:
    // 左
    case 8:
    // 左上
    case 9:
    // 左下
    case 12:
    // code
}

Similarly, if we have a series of switches controlled by a | b | c form than '{a: true, b: true, c: true}' simpler.

  • Bitwise AND &

    For each pair of bit operation is performed (AND). Only a and b is 1, a & b is 1. The following table 1 = 9 & 3

9 = 1 0 0 1
3 = 0 0 1 1
1 = 0 0 0 1

From the above table we can clearly be seen in bits rules, whereby a series of scenarios can lead

  1. Judgment parity
    We know that the last bit of the inevitable odd binary 1, so any odd & 1 must be equal to 1.
// 判断奇偶
return number & 1 === 1
  1. system Authority
    Business Scenario:
    We assume that there is a management system a, b, c, d four permissions, wherein each different accounts have different permissions (there may be one or more), e.g. admin account has a + b + c + d four permissions, guest users have permission b + c, that at this time how design should be easier to do so?

Bitwise AND: it is time to debut!

The basic idea:
rights are rights we use 0001, 0010, 0100, 1000 represents (ie, the most popular 1,2,4,8), if the admin user has a, b, c, d four permission, the admin is 1 | 2 | 4 | 8 = 15, and the guest user rights 4 | 8 = 12, it is determined whether the user has a permission can be judged as follows

admin & 4 === 4
admin & 8 === 8
admin & 2 === 2
admin & 1 === 1
  • Bitwise XOR ^

    For each bit, when the corresponding bit of the two operands, and only when there is a 1, the result is 1, and 0 otherwise.

== algorithm which corresponds to the binary addition without carry ==

9 = 1 0 0 1
3 = 0 0 1 1
10 = 1 0 1 0

Scenario:

  1. 1 0 variable switching and
    If we have a condition switched by a value 0 or 1
function update(toggle) {
    num = toggle ? 1 : 0;
}

update(true);


// 通过异或我们可以这么写
num = num ^ 1;
  1. Swap the values ​​of two variables (without third variable)
let a = 5,
    b = 6;

a = a ^ b;
b = a ^ b;
a = a ^ b;

// 还可以通过运算
a = a + b;
b = a - b;
a = a - b;

// es 6
[a, b] = [b, a]

Analysis Principle: a = a ^ b; b = a ^ b equivalent to b = a ^ b ^ b = a ^ (b ^ b) = a ^ 0 = a;

  1. Simple string encryption
  const key = 313;
  function encryption(str) {
      let s = '';
      str.split('').map(item => {
        s += handle(item);
      })
      return s;
  }
  
  function decryption(str) {
    let s = '';
    str.split('').map(item => {
        s += handle(item);
    })
    return s;
  }
  
  function handle(str) {
      if (/\d/.test(str)) {
        return str ^ key;
      } else {
        let code = str.charCodeAt();
        let newCode = code ^ key;
        return String.fromCharCode(newCode);
      }
  }

  let init = 'hello world 位运算';
  let result = encryption(init);             // őŜŕŕŖęŎŖŋŕŝę乴軩窮
  let decodeResult = decryption(result);     // hello world 位运算

Can be seen, we use an exclusive OR operation Unicode string value implements a brief string encryption effect.

== ps: the above code only demonstrates, the key and the decryption key should pass in the actual decryption. ==

  • Bitwise non ~

    For each bit of non-execution (NOT) operation. As a result of the NOT a reverse (i.e., inverted).

== ps: a value of x for any bitwise operation is a non - (x + 1). For example, the result is -6 to 5: ==

Negative form is stored using twos complement. The step of calculating two's complement binary numbers are three steps:

1. Determine the digital version of the non-negative binary representation (e.g., to calculate the twos complement -18, firstly to determine the binary representation of 18)

2. Anti-determined binary code, i.e., 0 should replace 1, the 1 is replaced with 0 (equivalent to ~ operation)

3. adding 1 to the inverted binary

We can see a number equivalent to a negation ~ a + 1, i.e., -a = ~ a + 1, so ~ a = - (a + 1)

Scenario:

  1. Rounding (rounding bit operation pattern)
~~(-5.88) // -5
  1. Determining whether there is an array
// 常用判断
if (arr.indexOf(item) > -1) {
    // code
}
// 按位非    ~-1 = - (-1 + 1)
if (~arr.indexOf(item)) {
    // code
}

Mobile bitwise operator

Bitwise mobile operator has two operands: the first number is to be moved, while the second is to move the length. Depending on the direction of movement of the different operators.

Conversion bit number of the mobile will first operate as a 32-bit integer big-endian order (big-endian order), and returns the same results as the left operand type. Right operand should be less than 32, otherwise, only the lowest 5 bytes will be used.

  • Left <<

    The operator will be the first operand to the left a specified number of bits movement. Left shifted out bits are discarded, with the right supplementary 0.

<< 2 illustrates operational example 3 as follows:
3 = 0000 0000 0000 0000 0,000,000,000,000,011
12 = 0000 0000 0000 0000 0,000,000,000,001,100

== ps: for any value of x in the left n, multiplied by the decimal equivalent in multiples of 10, here refers ==

x * 2^n

Scenario:

rgb and hexadecimal color conversion

First, we need to know the relationship between RGB and hexadecimal, for example, our most common white RGB expressed as rgb (255, 255, 255) , expressed as hexadecimal #FFFFFFF, we can put a hex color in addition to
'#' is divided into two part by outside, that is FF, FF, FF, FF look at the hexadecimal to decimal is how much? Yes, that is 255!

The understanding of the relationship between hexadecimal and RGB, we will find the RGB to hex method is very simple

  1. The RGB values ​​are converted to three hexadecimal, then splicing, i.e. rgb (255, 255, 255) => '#' + 'FF' + 'FF' + 'FF'.
  2. Clever use left, we hexadecimal value as an integer part, i.e. FFFFFF, we can understand FF0000 + FF00 + FF, as we explained above, if the left is calculated based on the hexadecimal, it can be appreciated for the FF << 4, FF << 2, FF, and in fact we turned it into a binary FF << 16, as follows:
x * 16^4  = x * 2 ^ 16

After understanding the principle, as follows:

function RGBToHex(rgb){
    // 取出rgb中的数值
    let arr = rgb.match(/\d+/g);
    if (!arr || arr.length !== 3) {
        console.error('rgb数值不合法');
        return
    }
    let hex = (arr[0]<<16 | arr[1]<<8 | arr[2]).toString(16);
    // 自动补全第一位
    if (hex.length < 6) {
        hex = '0' + hex;
    }
    return `#${hex}`;
}
  • Signed right shift >>

    The operator will first operand digits to the right of the specified movement. Rightward shifted out bits are discarded, the leftmost bit copied to fill the left. Since the new left-most bits are always the same as before, the sign bit is not changed. So called "spread symbols."

== ps: for any value of x in the right n, divided by the decimal equivalent in multiples of 10, after taking herein refers to an integer divided by the number ==

x / 2^n

Scenario:

Hex to RGB

Principle, see above RGB to hex

function hexToRGB(hex){
    if (!/^#([0-9a-fA-F]{3}){1,2}$/.test(hex)) {
        console.error('颜色不合法'); 
        return
    };
    // #f00 转为 #ff0000
    if (hex.length == 4) {
        hex = hex.replace(/([0-9a-fA-F])/g, '$1$1');
    };
    let num = hex.replace('#', '0x');
    let r = num >> 16;
    // 0xff = 255
    let g = num >> 8 & 0xff;
    let b = num  & 0xff;    
    return `rgb(${r},${g},${b})`;
}
  • Unsigned right shift >>>

    The operator will first operand digits to the right of the specified movement. Rightward shifted out bits are discarded, left filled with zeros. Because the sign bit becomes 0, so the result is always non-negative. (Annotation: 0 right even bits, the result is non-negative.)

    Digression

    Think of an algorithm in question before the Panel, the title is this:
    1. a frog can jump on a Class 1 level, you can also hop on level 2 ...... n It can also jump on stage. The frog jumped seeking a total of n grade level how many jumps?
    Problem-solving ideas are:

/ * Since the n steps, the first step there are n kinds of jump method: 1 skip, skip 2 to n stages hop
skip 1, the remaining level n-1, the remaining jumps is f (n-1 )
skip 2, the remaining n-2 stage, the remaining jumps is F (n-2)
so that f (n) = f (n -1) + f (n-2) + ... + f ( 1)
then f (n-1) = f (n-2) + f (n-3) + ... + f (1)

So the algorithm is:

function jumpFloorII(number){
    return 1<<(number-1);
}

WTF? What do you mean?
In fact, very simple, see the following procedure

f(n)=f(n-1)+f(n-2)+...+f(1)

f(n-1)=f(n-2)+f(n-3)+...+f(1)

F (n-) 2 = F (n-1). 4 = F (n-2-). 8 = F * (. 3-n-) ..... 2 = a (n-1) th power by f (1), Switch bit operation is the 1 << (n - 1)

Exercise: How to achieve the calendar check-ins

  1. How design can make a minimum of data
  2. Daily attendance should be how to update
  3. How to determine whether one day attendance

ps: the code word is not easy, if you think this article helpful to you, give praise it, ha ha ha ~

Guess you like

Origin www.cnblogs.com/mopagunda/p/11221928.html