在 Go 中解压 redis 设置位串

使用redis#Setbit像一键设置位:redis.Do("SETBIT", "mykey", 1, 1)

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

如何解压缩字符串以便在 Go 中获得一片布尔值?在 Ruby 中,你使用String#unpack就像"@".unpack它返回["00000010"]


繁星点点滴滴
浏览 219回答 1
1回答

慕婉清6462132

中没有这样的帮手redigo。这是我的实现:func hasBit(n byte, pos uint) bool {&nbsp; &nbsp; val := n & (1 << pos)&nbsp; &nbsp; return (val > 0)}func getBitSet(redisResponse []byte) []bool {&nbsp; &nbsp; bitset := make([]bool, len(redisResponse)*8)&nbsp; &nbsp; for i := range redisResponse {&nbsp; &nbsp; &nbsp; &nbsp; for j:=7; j>=0; j-- {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; bit_n := uint(i*8+(7-j))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; bitset[bit_n] = hasBit(redisResponse[i], uint(j))&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; return bitset}用法:&nbsp; &nbsp; response, _ := redis.Bytes(r.Do("GET", "testbit2"))&nbsp; &nbsp; for key, value := range getBitSet(response) {&nbsp; &nbsp; &nbsp; &nbsp; fmt.Printf("Bit %v = %v \n", key, value)&nbsp; &nbsp; }
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go