sen*_*hil 4 bit-manipulation bit go redis
使用redis#Setbit像一键设置位:redis.Do("SETBIT", "mykey", 1, 1)。
当我使用redis#Getlike 读取它时redis.Do("GET", "mykey"),我得到了一些字符串。
如何解压缩字符串,以便在Go中获得一小撮布尔值?在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
}
Run Code Online (Sandbox Code Playgroud)
用法:
response, _ := redis.Bytes(r.Do("GET", "testbit2"))
for key, value := range getBitSet(response) {
fmt.Printf("Bit %v = %v \n", key, value)
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
255 次 |
| 最近记录: |