英文:
Unpack redis set bit string in Go
问题
使用redis#Setbit来设置一个键中的位,例如:redis.Do("SETBIT", "mykey", 1, 1)。
当我使用redis#Get读取它,例如redis.Do("GET", "mykey"),我得到一个位字符串。
我该如何解包这个字符串,以便在Go中获得一个bool切片?在Ruby中,你可以使用String#unpack,例如"@".unpack,它会返回["00000010"]。
英文:
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"]
答案1
得分: 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)
}
请注意,这只是一个示例实现,可能需要根据你的具体需求进行调整。
英文:
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)
	}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论