May 30, 2021 Article blog
Convert the numbers into binary, then work with them, and then back to decimal
- // 1 的二进制表示为 00000000 00000000 00000000 00000001
- // 3 的二进制表示为 00000000 00000000 00000000 00000011
- // --------------------------------------------------
- // 1 的二进制表示为 00000000 00000000 00000000 00000001
- console.log(1 & 3) // 1
Convert the number to binary, then do or operate, and then back to decimal
- // 1 的二进制表示为 00000000 00000000 00000000 00000001
- // 3 的二进制表示为 00000000 00000000 00000000 00000011
- // --------------------------------------------------
- // 3 的二进制表示为 00000000 00000000 00000000 00000011
- console.log(1 | 3) // 3
Convert the number to binary, then make a different or operation, and then convert it back to decimal
- // 1 的二进制表示为 00000000 00000000 00000000 00000001
- // 3 的二进制表示为 00000000 00000000 00000000 00000011
- // --------------------------------------------------
- // 2 的二进制表示为 00000000 00000000 00000000 00000010
- console.log(1 ^ 3) // 2
Convert the number to binary, then do the non-operation, and then convert back to the decimal, which is also the binary anticode
- // 1 反码二进制表示为 11111111 11111111 11111111 11111110
- // 由于第一位(符号位)是1,所以这个数是负数。JavaScript 内部采用补码形式表示负数,即需要将这个数减去 1,再去一次反,然后加上负号才能得到这个负数对应的十进制数值
- // 1 的反码减一表示为 11111111 11111111 11111111 11111101
- // 取反 00000000 00000000 00000000 00000010
- // 表示为 -2
- console.log(~1) // -2
Convert the number to binary, then discard the high and make up 0 low
- // 1 的二进制表示为 00000000 00000000 00000000 00000001
- // 2 的二进制表示为 00000000 00000000 00000000 00000010
- console.log(1 << 1) // 2
Turn the number into binary, then discard the low bit and copy the leftmost bit to fill the left
- // 1 的二进制表示为 00000000 00000000 00000000 00000001
- // 0 的二进制表示为 00000000 00000000 00000000 00000000
- console.log(1 >> 1) // 0
Turn the number into binary, then discard the low bit and make up 0 on the left, so it is always non-negative.
For non-negative numbers, the results of symbolic right-shifting and unsigned right-shifting are always equal.
- // 偶数 & 1 = 0
- // 奇数 & 1 = 1
- console.log(2 & 1) // 0
- console.log(3 & 1) // 1
- console.log(~~6.83) // 6
- console.log(6.83 >> 0) // 6
- console.log(6.83 << 0) // 6
- console.log(6.83 | 0) // 6
- // 不可对负数取整
- console.log(6.83 >>> 0) // 6
- var a = 6
- var b = 8
-
- a ^= b
- b ^= a
- a ^= b
-
- console.log(a) // 8
- console.log(b) // 6
- function hexToRGB(hex: string): string{
- const hexx = hex.replace('#', '0x')
- const r = hexx >> 16
- const g = hexx >> 8 & 0xff
- const b = hexx & 0xff
- return `rgb(${r}, ${g}, ${b})`
- }
-
- function RGBToHex(rgb: string): string{
- const rgbArr = rgb.split(/[^\d]+/)
- const color = rgbArr[1] | rgbArr[2] << 8 | rgbArr[3]
- return `#${color.toString(16)}`
- }
Recommended lessons:
Little White Front End: JavaScript Zero Basic Getting Started to Advanced (2020 Edition)
JavaScript Live: Dynamic website development
Javascript mobile app live development