Postgresql 中文操作指南

8.10. Bit String Types #

位串是 1 和 0 的串。它们可用于存储或可视化位掩码。有两种 SQL 位类型:bit(_n)_ 和 bit varying(_n), where _n 是正整数。

Bit strings are strings of 1’s and 0’s. They can be used to store or visualize bit masks. There are two SQL bit types: bit(_n)_ and bit varying(_n), where _n is a positive integer.

bit 类型数据必须与长度 n 完全匹配;存储更短或更长的位串时出错。bit varying 数据最多可变长到最大长度 n;将拒绝较长的字符串。不带长度编写 bit 等同于 bit(1),而_bit varying_ 不带长度说明意味着长度无限制。

bit type data must match the length n exactly; it is an error to attempt to store shorter or longer bit strings. bit varying data is of variable length up to the maximum length n; longer strings will be rejected. Writing bit without a length is equivalent to bit(1), while bit varying without a length specification means unlimited length.

Note

如果明确将位串值强制转换为 bit(_n), it will be truncated or zero-padded on the right to be exactly _n 位,而不会引发错误。类似地,如果明确将位串值强制转换为 bit varying(_n), it will be truncated on the right if it is more than _n 位。

If one explicitly casts a bit-string value to bit(_n), it will be truncated or zero-padded on the right to be exactly _n bits, without raising an error. Similarly, if one explicitly casts a bit-string value to bit varying(_n), it will be truncated on the right if it is more than _n bits.

有关位字符串常量的语法信息,请参阅 Section 4.1.2.5。提供了位逻辑运算符和字符串操作函数;请参阅 Section 9.6

Refer to Section 4.1.2.5 for information about the syntax of bit string constants. Bit-logical operators and string manipulation functions are available; see Section 9.6.

Example 8.3. Using the Bit String Types

CREATE TABLE test (a BIT(3), b BIT VARYING(5));
INSERT INTO test VALUES (B'101', B'00');
INSERT INTO test VALUES (B'10', B'101');

ERROR:  bit string length 2 does not match type bit(3)

INSERT INTO test VALUES (B'10'::bit(3), B'101');
SELECT * FROM test;

  a  |  b
-----+-----
 101 | 00
 100 | 101

位字符串值每个8位组需要1个字节,另外根据字符串的长度需要5个或8个字节的开销(但长值可以压缩或移出,如 Section 8.3中关于字符字符串的解释)。

A bit string value requires 1 byte for each group of 8 bits, plus 5 or 8 bytes overhead depending on the length of the string (but long values may be compressed or moved out-of-line, as explained in Section 8.3 for character strings).