Reputation: 19285
Using redis#Setbit
to set bit in a key like: redis.Do("SETBIT", "mykey", 1, 1)
.
When I read it using redis#Get
like redis.Do("GET", "mykey")
, I get a bit string.
How do I unpack the string so I can get a slice of bools in Go? In Ruby, you use String#unpack like "@".unpack
which returns ["00000010"]
Upvotes: 4
Views: 857
Reputation: 31555
There is no such helper in redigo
. Here is my implementation:
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
}
Usage:
response, _ := redis.Bytes(r.Do("GET", "testbit2"))
for key, value := range getBitSet(response) {
fmt.Printf("Bit %v = %v \n", key, value)
}
Upvotes: 4