2015-05-16 53 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) 
    }