go的位运算
sukha 2 min read
位运算就是把二进制上下对齐,逐位计算:
var x uint8 = 1<<1 | 1<<5var y uint8 = 1<<1 | 1<<2fmt.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 = 00100010y = 00000110| 运算 | 规则 | 结果 |
|---|---|---|
x & y | 两位都是 1 才为 1 | 00000010 |
x | y | 至少一位是 1 就为 1 | 00100110 |
x ^ y | 两位不同才为 1 | 00100100 |
x &^ y | x 是 1、y 是 0 才为 1 | 00100000 |
位的编号从右往左,从 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。
评论 (0)
请先登录后再发表评论