go的位运算

sukha 2 min read

位运算就是把二进制上下对齐,逐位计算:

go
var x uint8 = 1<<1 | 1<<5
var y uint8 = 1<<1 | 1<<2
fmt.Printf("%08b\n", x) // "00100010", the set {1, 5}
fmt.Printf("%08b\n", y) // "00000110", the set {1, 2}
fmt.Printf("%08b\n", x&y) // "00000010", the intersection {1}
fmt.Printf("%08b\n", x|y) // "00100110", the union {1, 2, 5}
fmt.Printf("%08b\n", x^y) // "00100100", the symmetric difference {2, 5}
fmt.Printf("%08b\n", x&^y) // "00100000", the difference {5}
for i := uint(0); i < 8; i++ {
if x&(1<<i) != 0 { // membership test
fmt.Println(i) // "1", "5"
}
}
fmt.Printf("%08b\n", x<<1) // "01000100", the set {2, 6}
fmt.Printf("%08b\n", x>>1) // "00010001", the set {0, 4}
x = 00100010
y = 00000110
运算规则结果
x & y两位都是 1 才为 100000010
x | y至少一位是 1 就为 100100110
x ^ y两位不同才为 100100100
x &^ yx 是 1、y 是 0 才为 100100000

位的编号从右往左,从 0 开始:

  • 1 << i:把 1 移到第 i 位。
  • x & (1 << i) != 0:检查 x 的第 i 位是不是 1,因此循环打印 1、5。
  • x << 1:整体左移一位,右边补 0 → 01000100。
  • x >> 1:整体右移一位,左边补 0 → 00010001。

%08b:用二进制显示,不足 8 位就在左边补 0。

后记

My avatar

感谢你读到这里。

这座小站更像一份持续维护的“终端笔记”:记录我解决问题的过程,也记录走过的弯路。


More Posts

评论

评论 (0)

请先登录后再发表评论

加载中...