gpt4 book ai didi

有人可以解释 redis setbit 命令吗?

转载 作者:IT王子 更新时间:2023-10-29 05:57:39 25 4
gpt4 key购买 nike

> setbit mykey 1 1
> setbit mykey 7 1

当我将字符串值 1 和 7 存储到“mykey”中时,redis 中到底存储了什么?以及 getbit 在 redis 中是如何工作的?

有人尝试在这个值中循环这个位吗?我知道 bitcount 会给我数字 2,但我也想从中得到准确的字符串值 1 和 7,这可能吗?

--

我通过使用 erlang redis 客户端读取输出做了一些实验。

> setbit mykey 1 1

二郎输出:

<<"@">>

然后我删除这个条目:

> del mykey

我做同样的事情来偏移 2 4 8,在这里你可以看到映射:

When offset is 1, the output is <<"@">>;
When offset is 2, the output is <<" ">>;
When offset is 4, the output is <<"\b">>;
When offset is 8, the output is <<0,128>>;

老实说,我现在更糊涂了。

或者有人可以解释这个"bitops.c"

-- 更新 ---

也许我应该提一下我想这样做的原因,以使问题更清楚。我们都知道用位图来存储在线用户会很酷。我想要做的是从 redis 存储的内容中获取准确的在线用户 ID。

刚刚完成一个quick version从 redis 中提取偏移量。请随时改进它。

最佳答案

正如其名称所暗示的,SETBIT 允许您执行位操作 - 即对于给定的键,在给定的位偏移处将给定的位设置为 0 或 1。

重要的是要理解结果并不总是只包含可打印字符。这就是 Redis 使用 custom function sdscatrepr 的原因格式化 CLI 输出:

Append to the sds string "s" an escaped string representation where all the non-printable characters (tested with isprint()) are turned into escapes in the form "\n\r\a...." or "\x".

话虽如此,让我们从一个简单的例子开始。如果考虑十六进制数 0x7F (= 127),它的 8 位二进制表示是:

pos: 0 1 2 3 4 5 6 7
bit: 0 1 1 1 1 1 1 1
^ ^
| |
MSB LSB

您通常可以使用 SETBIT 来存储此值,请记住偏移量 0MSB 而偏移量 7 是 LSB :

redis> SETBIT myval 0 0
(integer) 0
redis> SETBIT myval 1 1
(integer) 0
redis> SETBIT myval 2 1
(integer) 0
redis> SETBIT myval 3 1
(integer) 0
redis> SETBIT myval 4 1
(integer) 0
redis> SETBIT myval 5 1
(integer) 0
redis> SETBIT myval 6 1
(integer) 0
redis> SETBIT myval 7 1
(integer) 0

获取您的值(value)以检查是否:

redis> GET myval
"\x7f"

现在多字节会发生什么?假设您要存储 0x52 (= 82),它对应于 ASCII 中的字符 R。 8 位表示是 01010010,位位置为 (8, 9, ..., 15),因为我们希望它存储在第一个值之后:

redis> SETBIT myval 8 0
(integer) 0
redis> SETBIT myval 9 1
(integer) 0
redis> SETBIT myval 10 0
(integer) 0
redis> SETBIT myval 11 1
(integer) 0
redis> SETBIT myval 12 0
(integer) 0
redis> SETBIT myval 13 0
(integer) 0
redis> SETBIT myval 14 1
(integer) 0
redis> SETBIT myval 15 0
(integer) 0

你得到:

redis> GET myval
"\x7fR"

这里 Redis CLI 能够表示可打印字符 R

When I store string value 1 and 7 into "mykey"

它对应于 01000001 等于 65 和十六进制的 0x41。它对应于 ASCII 字符 A。这样做:

redis> SETBIT mykey 1 1
(integer) 0
redis> SETBIT mykey 7 1
(integer) 0

给予:

redis> GET mykey
"A"

how the getbit works inside redis?

它只是返回给定位置的位值。这里:

redis> GETBIT mykey 1
(integer) 1

但是 bit 0 没有设置(默认为 0)因此:

redis> GETBIT mykey 0
(integer) 0

关于有人可以解释 redis setbit 命令吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20673131/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com