Last active
December 7, 2021 02:20
-
-
Save axiaoxin/96520f9dfb2632ea7c6bd005d0f73829 to your computer and use it in GitHub Desktop.
go-redis bitmap demo
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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