Golang 位操作符总结
位运算可能在平常的编程中使用的并不多,但涉及到底层优化,一些算法及源码可能会经常遇见,下面先回顾一下位操作符的基础:
与操作:&
1 & 1 = 1
1 & 0 = 0
0 & 1 = 0
0 & 0 = 0
或操作:!
1 | 1 = 1
1 | 0 = 1
0 | 1 = 1
0 & 0 = 0
异或:^
1 ^ 1 = 0
1 ^ 0 = 1
0 ^ 1 = 1
0 ^ 0 = 0
左移:<<
1 << 10 = 1024
1 << 20 = 1M
1 << 30 = 1G
右移:>>
1024 >> 10 = 1
1024 >>1 = 512
1024 >>2 = 256
package main
import (
"fmt"
)
type users struct {
name string
flag uint8
vip bool
svip bool
blue bool
red bool
yellow bool
}
func setVip(user users) users {
user.vip = true
return user
}
func isVip(user users) {
if user.vip {
fmt.Println("user is vip")
} else {
fmt.Println("user is not vip")
}
}
func binaryTest() {
var user users
user.name = "test01"
user.vip = true
isVip(user)
user.vip = false
isVip(user)
}
func main() {
binaryTest()
}
这种实现方式也可以,但是明显我们需要为每个类型都做操作,并且如果以后又有更多的各种各样的会员和钻有需要添加新的,所以并不是最佳方法,下面我们通过位操作来实现上述的功能,代码如下:
package main
import (
"fmt"
)
type users struct {
name string
flag uint8
}
// 这里通过位移的方式默认00000 从左边一次为vip,svip,blue,red,yellow
const (
vip = 1
svip = (1 << 1)
blue = (1 << 2)
red = (1 << 3)
yello = (1 << 4)
)
// setFlag 用于设置用户开通了哪些特权
func setFlag(user users, isSet bool, typeFlag uint8) users {
if isSet == true {
user.flag = user.flag | typeFlag
} else {
user.flag = user.flag ^ typeFlag
}
return user
}
//isFlag 用于判断用户是否开通某项特权
func isFlag(user users, typeFlag uint8) bool {
result := user.flag & typeFlag
return result == typeFlag
}
func binaryTest() {
var user users
user.name = "coder"
user.flag = 0
//判断用户是否是vip
result := isFlag(user, vip)
fmt.Printf("user is Vip:%t\n", result)
//给用户开通vip,并看用户是否开通vip
user = setFlag(user, true, vip)
result = isFlag(user, vip)
fmt.Printf("user is Vip:%t\n", result)
//取消用户的vip,并查看用户是否还是vip
user = setFlag(user, false, vip)
result = isFlag(user, vip)
fmt.Printf("user is Vip:%t\n", result)
}
func main() {
binaryTest()
}