由 John Doe 六月 18, 2025
你需要在 PostgreSQL 中对数字进行进制转换吗?
特性提交日志
添加 to_bin() 和 to_oct()。
本次提交引入了将数字转换为其等效的二进制和八进制表示形式的函数。此外,这些函数和 to_hex() 函数相关的基数转换代码已被移至一个通用辅助函数中。
讨论:https://postgr.es/m/Y6IyTQQ/TsD5wnsH%40vm3.eradman.com
示例
从很早的版本开始,PostgreSQL 就提供了 to_hex 函数:
select to_hex(1234567);
to_hex
--------
12d687
(1 row)
现在,新的版本中有了与之互补的处理二进制和八进制数字的函数:
select to_bin(1234567), to_oct(1234567);
to_bin | to_oct
-----------------------+---------
100101101011010000111 | 4553207
(1 row)
这些函数(全部三个)都不能处理小数:
select to_hex(1.1);
ERROR: function to_hex(numeric) does not exist
LINE 1: select to_hex(1.1);
^
HINT: No function matches the given name and argument types. You might need to add explicit type casts.
在添加这些函数的同时,文档也进行了补充:所有这些函数,包括旧的 to_hex,都使用补码表示。这意味着负数的表示可能会让一些人感到意外:
select i, to_hex(i), to_bin(i), to_oct(i) from unnest('{1,0,-1}'::int4[]) i;
i | to_hex | to_bin | to_oct
----+----------+----------------------------------+-------------
1 | 1 | 1 | 1
0 | 0 | 0 | 0
-1 | ffffffff | 11111111111111111111111111111111 | 37777777777
(3 rows)
现在,你可能会问:如何进行反向转换?很简单,只需在数值前加上:
- 0x – 用于十六进制值
- 0o – 用于八进制值
- 0b – 用于二进制值
如下所示:
select '0xdecaf'::int4;
int4
--------
912559
(1 row)
select '0o666'::int4;
int4
------
438
(1 row)
select '0b10101010'::int4;
int4
------
170
(1 row)
非常不错的新特性,这将会方便很多开发人员的工作。感谢社区的所有相关人员。
参考
提交日志:https://git.postgresql.org/pg/commitdiff/260a1f18dae8729f99cefe4e1f759193fd6bedd0