Taiyi's Blog

Bit Manipulation

March 17, 2023(May 29, 2023更新)

  • 找到最低位的1

    n & -n
    /*
    6 ^ -6 = 110 ^ 010 = 010
    */
  • 消掉最低位的1

    n & (n-1)
  • 檢查是不是2n2^n

    const isPowerOfTwo = (x !== 0) && ((n & (n - 1) === 0))

XOR

  • Swap two varibles

    a = 4
    b = 6
    a = a ^ b
    b = a ^ b
    a = a ^ b
    console.log(a, b) // 6 4

Reference


Taiyi 目前正在鉅亨擔任前端打工仔