Skip to content

Instantly share code, notes, and snippets.

@axiaoxin
Last active December 7, 2021 02:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save axiaoxin/96520f9dfb2632ea7c6bd005d0f73829 to your computer and use it in GitHub Desktop.
Save axiaoxin/96520f9dfb2632ea7c6bd005d0f73829 to your computer and use it in GitHub Desktop.
go-redis bitmap demo
func appendBytes(bs []byte, b byte) []byte {
var a byte
for i := 0; i < 8; i++ {
a = b
b <<= 1
b >>= 1
switch a {
case b:
bs = append(bs, '0')
default:
bs = append(bs, '1')
}
b <<= 1
}
return bs
}
// BitmapBytesToBytes bitmap 转 bytes
func BitmapBytesToBytes(bs []byte) []byte {
l := len(bs)
bl := l*8 + l + 1
buf := make([]byte, 0, bl)
for _, b := range bs {
buf = appendBytes(buf, b)
}
return buf
}
func TestBitmap(t *testing.T) {
ctx := context.Background()
RedisClient := redis.NewClient(&redis.Options{
Addr: "10.10.8.143:6379",
Password: "aGGewe8wmJ",
DB: 1,
})
RedisClient.SetBit(ctx, "key_bitmap", 0, 0)
RedisClient.SetBit(ctx, "key_bitmap", 1, 1)
RedisClient.SetBit(ctx, "key_bitmap", 2, 0)
RedisClient.SetBit(ctx, "key_bitmap", 3, 0)
RedisClient.SetBit(ctx, "key_bitmap", 4, 1)
RedisClient.SetBit(ctx, "key_bitmap", 5, 1)
RedisClient.SetBit(ctx, "key_bitmap", 6, 0)
res, _ := RedisClient.Get(ctx, "key_bitmap").Bytes()
// way1
b := BitmapBytesToBytes(res)
fmt.Printf("%s\n", b) //01001100
// way2
var bits string
for _, v := range res {
bits = fmt.Sprintf("%s%0.8b", bits, v)
}
fmt.Printf("%s\n", bits) // 01001100
r, _ := RedisClient.BitCount(ctx, "key_bitmap", &redis.BitCount{
Start: 0, // PS: byte index, not bit index
End: 1,
}).Result()
fmt.Println(r) // 3
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment