取反运算简单使用


取反运算简单使用

参考:

  1. https://zhuanlan.zhihu.com/p/261080329
  2. https://blog.csdn.net/qq_19272431/article/details/78564391
// 推断:
// 1. 计算机中的位运算都是补码运算,因为数字存储到计算机的时候都是以补码形式存储
// 2. ~a = -(a+1)
// 3. ~(a - 1) = -a
const a = 0b1111_1000

const b =  ~(a - 1)
console.log(a) // 248
console.log(b) // -248
console.log((a & b)) // 8

// 0000 0000 1111 1000 a 补码(因为是正数,补码==原码)248
// 0000 0000 1111 0111 a - 1
// 1111 1111 0000 1000 ~(a - 1) 补码
// 1111 1111 0000 0111 ~(a - 1) 反码
// 1111 1111 1111 1000 ~(a - 1) 原码 -248
// 0000 0000 0000 1000 a & b 8

console.log(~(2 - 1)) // -2
console.log(~(-2 - 1)) // 2
// 2 0000 0010 原码
// 2 0000 0010 补码
// ~2 1111 1101 取反 补码
// ~2 1111 1100 反码
// ~2 1000 0011 取反 原码 得出结果-3