4

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"]

sent-hil
  • 18,635
  • 16
  • 56
  • 74
  • 2
    Does the following work for you: https://play.golang.org/p/64GjaXNar2 ? –  May 16 '15 at 11:23

1 Answers1

4

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)
    }
Max Malysh
  • 29,384
  • 19
  • 111
  • 115