2015-05-16 51 views
4

使用redis#Setbit设置位中的位如:redis.Do("SETBIT", "mykey", 1, 1)解压redis在Go中设置位串

当我使用redis#Get(如redis.Do("GET", "mykey"))读取它时,我得到了一个字符串。

如何解开字符串以便我可以在Go中找到一块布尔?在Ruby中,您使用String#unpack,如"@".unpack,它返回["00000010"]

+1

为您做了以下工作:https://play.golang.org/p/64GjaXNar2? –

+0

是的,它的工作原理。谢谢! –

回答

4

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) 
    }