使用redis#Setbit
设置密钥位,如:redis.Do("SETBIT", "mykey", 1, 1)
。
当我使用redis#Get
如redis.Do("GET", "mykey")
读取它时,我得到一个位字符串。
我如何解包字符串,以便我可以在Go中获得一个bool切片?在Ruby中,您使用String#unpack,如"@".unpack
,它返回["00000010"]
在redigo
中没有这样的帮助器。下面是我的实现:
func hasBit(n byte, pos uint) bool {
val := n & (1 << pos)
return (val > 0)
}
func getBitSet(redisResponse []byte) []bool {
bitset := make([]bool, len(redisResponse)*8)
for i := range redisResponse {
for j:=7; j>=0; j-- {
bit_n := uint(i*8+(7-j))
bitset[bit_n] = hasBit(redisResponse[i], uint(j))
}
}
return bitset
}
用法:
response, _ := redis.Bytes(r.Do("GET", "testbit2"))
for key, value := range getBitSet(response) {
fmt.Printf("Bit %v = %v n", key, value)
}