本文内容为 http://redis.io/commands/bitop 的翻译、注解、例子扩充及其它修改。感谢 Redis 作者 Antirez 为开源社区作出的贡献,本文保证最新、最准、最全以表示对其的敬意。欢迎留言纠错、提示更新或支持。
BITOP operation destkey key [key ...]

对多个键(值为字符串)进行按位运算操作(Bitwise operation),并将结果保存至目标键中。

Perform a bitwise operation between multiple keys (containing string values) and store the result in the destination key.

BITOP 命令支持四种类型的按位操作运算:ANDORXORNOT,对应的有效调用方式为:

  • BITOP AND destkey srckey1 srckey2 srckey3 ... srckeyN
  • BITOP OR destkey srckey1 srckey2 srckey3 ... srckeyN
  • BITOP XOR destkey srckey1 srckey2 srckey3 ... srckeyN
  • BITOP NOT destkey srckey

正如所见,只有 NOT 运算是特殊的,它只需要 1 个输入键(Input key)

As you can see NOT is special as it only takes an input key, because it performs inversion of bits so it only makes sense as an unary operator.

该操作的结果总是保存在目标键 destkey 中。

The result of the operation is always stored at destkey.
  • 存储到目标键中的字符串的长度,即等值于最长输入字符串的大小。

    The size of the string stored in the destination key, that is equal to the size of the longest input string.
  • redis>SET foo1 bar
    OK
    redis>SET foo2 aar
    OK
    redis>BITOP OR res foo1 foo2
    (integer) 3
    redis>GET res
    "car"
    redis>SET foo1 ClassFoo
    OK
    redis>SET foo2 ClassBar
    OK
    redis>BITOP OR foo foo1 foo2
    (integer) 8
    redis>GET foo
    "ClassFo\x7f"
  • 版本支持

    2.6.0+

    时间复杂度(Time complexity)

    O(N)

    其它

    在处理不同长度字符串时,如果一个字符串长度短于最长字符串的长度,将按用假想 0 值填充至该最大长度的方式对待。

    When an operation is performed between strings having different lengths, all the strings shorter than the longest string in the set are treated as if they were zero-padded up to the length of the longest string.

    该点对不存在的键同样适用。

    The same holds true for non-existent keys, that are considered as a stream of zero bytes up to the length of the longest string.