PostgreSQL Oracle 兼容性之 - BIT_TO_NUM , BITAND , 比特运算 , 比特与整型互相转换

本文涉及的产品
云原生数据库 PolarDB MySQL 版,Serverless 5000PCU 100GB
云原生数据库 PolarDB 分布式版,标准版 2核8GB
云数据库 RDS MySQL Serverless,0.5-2RCU 50GB
简介:

背景

比特类型转换为整型,整型转换为比特类型,以及整型的比特运算。

在数据分析时被经常使用,例如对多个用0和1表示的标签字段叠加,使用一个整型表示。

又或者将数字表述的标签信息转换为比特位,以获取分散的标签信息。

在Oracle中可以使用bit_to_num将多个0,1转换为number,使用bitand对两个number进行比特与运算得到另一个number。

  • bit_to_num(exp1, exp2, ...., expn)

    BIN_TO_NUM converts a bit vector to its equivalent number. Each argument to this function represents a bit in the bit vector.

    This function takes as arguments any numeric datatype, or any nonnumeric datatype that can be implicitly converted to NUMBER.

    Each expr must evaluate to 0 or 1.

    This function returns Oracle NUMBER.

例子

SELECT BIN_TO_NUM(1,0,1,0) FROM DUAL; 

BIN_TO_NUM(1,0,1,0)
-------------------
                 10
  • BITAND(exp1, exp2)

    The BITAND function treats its inputs and its output as vectors of bits; the output is the bitwise AND of the inputs.

    The types of expr1 and expr2 are NUMBER, and the result is of type NUMBER. If either argument to BITAND is NULL, the result is NULL.

    The arguments must be in the range -(2(n-1)) .. ((2(n-1))-1). If an argument is out of this range, the result is undefined.

    The result is computed in several steps. First, each argument A is replaced with the value SIGN(A)*FLOOR(ABS(A)).

    This conversion has the effect of truncating each argument towards zero. Next, each argument A (which must now be an integer value) is converted to an n-bit two's complement binary integer value.

    The two bit values are combined using a bitwise AND operation. Finally, the resulting n-bit two's complement value is converted back to NUMBER.

例子

SELECT BITAND(6,3) FROM DUAL;

BITAND(6,3)
-----------
          2

SELECT BITAND(
   BIN_TO_NUM(1,1,0),
   BIN_TO_NUM(0,1,1)) "Binary"
FROM DUAL;

    Binary
----------
         2

PostgreSQL BIT_TO_NUM

PostgreSQL的bit转换为整型有隐式的转换,与显示的转换。

固定长度的bit到整型是可以使用隐式转换的,而varbit到整型则需要显示转换。

隐式转换例子

postgres=# select '1010'::bit(4)::int;
 int4 
------
   10
(1 row)

postgres=# select '1010'::varbit::int;
ERROR:  cannot cast type bit varying to integer
LINE 1: select '1010'::varbit::int;
                             ^

显示转换例子

postgres=# select int4(bit(4) '1010');
 int4 
------
   10
(1 row)

postgres=# select int4(varbit(4) '1010');
 int4 
------
   10
(1 row)

postgres=# select int4(varbit '1010');
 int4 
------
   10
(1 row)

自定义bit_to_num函数,注意它是动态输入变量

postgres=# create or replace function bit_to_num(VARIADIC arr int[]) returns numeric as $$
declare
  mid int2; res numeric;
begin
  foreach mid in array arr
  loop
    if mid not in (0,1) then
      raise 'must 1 or 0';
    end if;
  end loop;
  res := (int8(array_to_string(arr,'')::varbit))::numeric;
  return res;
end;
$$ language plpgsql;
CREATE FUNCTION

测试

postgres=# select bit_to_num(1,0,1,0,1,0,2);
ERROR:  must 1 or 0

postgres=# select bit_to_num(1,0,1,0);
 bit_to_num 
------------
         10
(1 row)

PostgreSQL 多种类型 bitnot bitand bitor bitxor bit 左右移动

PostgreSQL 有操作符直接支持整型、BIT类型以及MAC地址类型的比特操作,如下

                                                                                             List of operators
   Schema   | Name |        Left arg type        |       Right arg type        |         Result type         |         Function         |                           Description                            
------------+------+-----------------------------+-----------------------------+-----------------------------+--------------------------+------------------------------------------------------------------
 pg_catalog | #    | bigint                      | bigint                      | bigint                      | int8xor                  | bitwise exclusive or
 pg_catalog | #    | bit                         | bit                         | bit                         | bitxor                   | bitwise exclusive or
 pg_catalog | #    | integer                     | integer                     | integer                     | int4xor                  | bitwise exclusive or
 pg_catalog | #    | smallint                    | smallint                    | smallint                    | int2xor                  | bitwise exclusive or
 pg_catalog | &    | bigint                      | bigint                      | bigint                      | int8and                  | bitwise and
 pg_catalog | &    | bit                         | bit                         | bit                         | bitand                   | bitwise and
 pg_catalog | &    | inet                        | inet                        | inet                        | inetand                  | bitwise and
 pg_catalog | &    | integer                     | integer                     | integer                     | int4and                  | bitwise and
 pg_catalog | &    | macaddr                     | macaddr                     | macaddr                     | macaddr_and              | bitwise and
 pg_catalog | &    | smallint                    | smallint                    | smallint                    | int2and                  | bitwise and
 pg_catalog | <<   | bigint                      | integer                     | bigint                      | int8shl                  | bitwise shift left
 pg_catalog | <<   | bit                         | integer                     | bit                         | bitshiftleft             | bitwise shift left
 pg_catalog | <<   | integer                     | integer                     | integer                     | int4shl                  | bitwise shift left
 pg_catalog | <<   | smallint                    | integer                     | smallint                    | int2shl                  | bitwise shift left
 pg_catalog | >>   | bigint                      | integer                     | bigint                      | int8shr                  | bitwise shift right
 pg_catalog | >>   | bit                         | integer                     | bit                         | bitshiftright            | bitwise shift right
 pg_catalog | >>   | integer                     | integer                     | integer                     | int4shr                  | bitwise shift right
 pg_catalog | >>   | smallint                    | integer                     | smallint                    | int2shr                  | bitwise shift right
 pg_catalog | |    | bigint                      | bigint                      | bigint                      | int8or                   | bitwise or
 pg_catalog | |    | bit                         | bit                         | bit                         | bitor                    | bitwise or
 pg_catalog | |    | inet                        | inet                        | inet                        | inetor                   | bitwise or
 pg_catalog | |    | integer                     | integer                     | integer                     | int4or                   | bitwise or
 pg_catalog | |    | macaddr                     | macaddr                     | macaddr                     | macaddr_or               | bitwise or
 pg_catalog | |    | smallint                    | smallint                    | smallint                    | int2or                   | bitwise or
 pg_catalog | ~    |                             | bigint                      | bigint                      | int8not                  | bitwise not
 pg_catalog | ~    |                             | bit                         | bit                         | bitnot                   | bitwise not
 pg_catalog | ~    |                             | inet                        | inet                        | inetnot                  | bitwise not
 pg_catalog | ~    |                             | integer                     | integer                     | int4not                  | bitwise not
 pg_catalog | ~    |                             | macaddr                     | macaddr                     | macaddr_not              | bitwise not
 pg_catalog | ~    |                             | smallint                    | smallint                    | int2not                  | bitwise not

例子

postgres=# select 6&3;
 ?column? 
----------
        2
(1 row)

postgres=# select 6|3;
 ?column? 
----------
        7
(1 row)

postgres=# select 6#3;
 ?column? 
----------
        5
(1 row)

postgres=# select ~6;
 ?column? 
----------
       -7
(1 row)

postgres=# select 6<<1;
 ?column? 
----------
       12
(1 row)

postgres=# select 6>>1;
 ?column? 
----------
        3
(1 row)

如果你要和ORACLE用法完全一致,可以自定义bitand函数,或者使用orafce插件来支持.

例子

postgres=# create or replace function bitand(numeric,numeric) returns numeric as $$
select ($1::int8 & $2::int8)::numeric ;
$$ language sql strict;
CREATE FUNCTION

postgres=# select bitand(6,3);
 bitand 
--------
      2
(1 row)

PostgreSQL 如何将numeric转换为varbit

第一种方法如下, 涉及符号与类型宽度(假设int为signed int).

do language plpgsql $$
declare
  o_bit text;
  o_len int;
  i_num int;
  i_conv int;
  i_num_abs int;
  i_res int;
  i_mod int;
begin
  o_len := 32;
  i_num := -10234;
  i_conv := 2;
  i_num_abs := abs(i_num);
  i_res := i_num_abs/i_conv;
  i_mod := mod(i_num_abs,i_conv);
  o_bit := i_mod::text;
  loop
    if i_res = 0 then
      exit;
    end if;
    i_mod := mod(i_res,i_conv);
    i_res := i_res/i_conv;
    o_bit := i_mod||o_bit;
  end loop;
  o_len := o_len - char_length(o_bit) - 1;
  o_bit := repeat('0', o_len)||o_bit;
  if i_num >=0 then
    o_bit := '0'||o_bit;
  else
    o_bit := '1'||o_bit;
  end if;
  raise notice '%', o_bit;
end;
$$;

创建函数如下 :

create or replace function i4tob(i_num int) returns varbit as $$
declare
  o_bit text;
  o_len int;
  i_conv int;
  i_num_abs int;
  i_res int;
  i_mod int;
begin
  o_len := 32;
  i_conv := 2;
  i_num_abs := abs(i_num);
  i_res := i_num_abs/i_conv;
  i_mod := mod(i_num_abs,i_conv);
  o_bit := i_mod::text;
  loop
    if i_res = 0 then
      exit;
    end if;
    i_mod := mod(i_res,i_conv);
    i_res := i_res/i_conv;
    o_bit := i_mod||o_bit;
  end loop;
  o_len := o_len - char_length(o_bit) - 1;
  if i_num >=0 then
    null;
  else
    o_bit := repeat('0', o_len)||o_bit;
    o_bit := '1'||o_bit;
  end if;
  raise notice '%', o_bit;
  return o_bit::varbit;
end;
$$ language plpgsql;

测试 :

postgres=# select i4tob(-100);
NOTICE:  10000000000000000000000001100100
              i4tob               
----------------------------------
 10000000000000000000000001100100
(1 row)

postgres=# select i4tob(100);
NOTICE:  1100100
  i4tob  
---------
 1100100
(1 row)

postgres=# select i4tob(256);
NOTICE:  100000000
   i4tob   
-----------
 100000000
(1 row)

postgres=# select i4tob(-256);
NOTICE:  10000000000000000000000100000000
              i4tob               
----------------------------------
 10000000000000000000000100000000
(1 row)

另一种方法是使用位移算法 :

do language plpgsql $$
declare
  o_bit text;
  o_len int;
  i_num int;
  i_conv int;
  i_num_abs int;
  i_pos int;
begin
  o_len := 32;
  i_num := -1024;
  i_conv := 2;
  i_num_abs := abs(i_num);
  i_pos := trunc((dlog1(i_num_abs))/0.693147180559945);
  o_bit := mod(i_num_abs,i_conv)::text;
  if i_pos >= 1 then
    for i in 1..i_pos loop
      o_bit := mod(i_num_abs>>i, i_conv)||o_bit;
    end loop;
  end if;
  if i_num >=0 then
    null;
  else
    o_len := o_len - char_length(o_bit) - 1;
    o_bit := repeat('0', o_len)||o_bit;
    o_bit := '1'||o_bit;
  end if;
  raise notice '%', o_bit;
end;
$$;

改成函数 :

create or replace function si32tob(i_num int) returns varbit as $$
declare
  o_bit text;
  o_len int;
  i_conv int;
  i_num_abs int;
  i_pos int;
begin
  o_len := 32;
  i_conv := 2;
  i_num_abs := abs(i_num);
  i_pos := trunc((dlog1(i_num_abs))/0.693147180559945);
  o_bit := mod(i_num_abs,i_conv)::text;
  if i_pos >= 1 then
    for i in 1..i_pos loop
      o_bit := mod(i_num_abs>>i, i_conv)||o_bit;
    end loop;
  end if;
  if i_num >=0 then
    null;
  else
    o_len := o_len - char_length(o_bit) - 1;
    o_bit := repeat('0', o_len)||o_bit;
    o_bit := '1'||o_bit;
  end if;
  raise notice '%', o_bit;
  return o_bit::varbit;
end;
$$ language plpgsql;

测试 :

digoal=# select si32tob(1);
NOTICE:  1
 si32tob 
---------
 1
(1 row)
Time: 1.715 ms
digoal=# select si32tob(2);
NOTICE:  10
 si32tob 
---------
 10
(1 row)
Time: 1.049 ms
digoal=# select si32tob(-2);
NOTICE:  10000000000000000000000000000010
             si32tob              
----------------------------------
 10000000000000000000000000000010
(1 row)
Time: 1.520 ms
digoal=# select si32tob(234);
NOTICE:  11101010
 si32tob  
----------
 11101010
(1 row)
Time: 1.094 ms
digoal=# select si32tob(-234);
NOTICE:  10000000000000000000000011101010
             si32tob              
----------------------------------
 10000000000000000000000011101010
(1 row)
Time: 1.124 ms

以上函数参考wikihow提供的算法编写.

其他转换可参考本文末尾的函数进行修改.

参考

1. http://docs.oracle.com/cd/B28359_01/server.111/b28286/functions013.htm

2. http://docs.oracle.com/cd/B28359_01/server.111/b28286/functions014.htm

3. http://www.wikihow.com/Convert-from-Decimal-to-Binary

4. http://psoug.org/snippet/Convert-between-Decimal-Binary-Octal-and-Hex_536.htm

5. src/backend/optimizer/path/costsize.c

00096 #define LOG2(x)  (log(x) / 0.693147180559945)

6. oracle pl/sql 相关转换函数

SET serveroutput ON

CREATE OR REPLACE PACKAGE dbms_numsystem AS
   FUNCTION bin2dec (binval IN CHAR  ) RETURN NUMBER;
   FUNCTION dec2bin (N      IN NUMBER) RETURN VARCHAR2; 
   FUNCTION oct2dec (octval IN CHAR  ) RETURN NUMBER;
   FUNCTION dec2oct (N      IN NUMBER) RETURN VARCHAR2; 
   FUNCTION hex2dec (hexval IN CHAR  ) RETURN NUMBER;
   FUNCTION dec2hex (N      IN NUMBER) RETURN VARCHAR2; 
END dbms_numsystem;
/
show errors

CREATE OR REPLACE PACKAGE BODY dbms_numsystem AS

FUNCTION bin2dec (binval IN CHAR) RETURN NUMBER IS
  i                 NUMBER;
  digits            NUMBER;
  result            NUMBER := 0;
  current_digit     CHAR(1);
  current_digit_dec NUMBER;
BEGIN
  digits := LENGTH(binval);
  FOR i IN 1..digits LOOP
     current_digit := SUBSTR(binval, i, 1);
     current_digit_dec := TO_NUMBER(current_digit);
     result := (result * 2) + current_digit_dec;
  END LOOP;
  RETURN result;
END bin2dec;

FUNCTION dec2bin (N IN NUMBER) RETURN VARCHAR2 IS
  binval VARCHAR2(64);
  N2     NUMBER := N;
BEGIN
  WHILE ( N2 > 0 ) LOOP
     binval := MOD(N2, 2) || binval;
     N2 := TRUNC( N2 / 2 );
  END LOOP;
  RETURN binval;
END dec2bin;

FUNCTION oct2dec (octval IN CHAR) RETURN NUMBER IS
  i                 NUMBER;
  digits            NUMBER;
  result            NUMBER := 0;
  current_digit     CHAR(1);
  current_digit_dec NUMBER;
BEGIN
  digits := LENGTH(octval);
  FOR i IN 1..digits LOOP
     current_digit := SUBSTR(octval, i, 1);
     current_digit_dec := TO_NUMBER(current_digit);
     result := (result * 8) + current_digit_dec;
  END LOOP;
  RETURN result;
END oct2dec;

FUNCTION dec2oct (N IN NUMBER) RETURN VARCHAR2 IS
  octval VARCHAR2(64);
  N2     NUMBER := N;
BEGIN
  WHILE ( N2 > 0 ) LOOP
     octval := MOD(N2, 8) || octval;
     N2 := TRUNC( N2 / 8 );
  END LOOP;
  RETURN octval;
END dec2oct;

FUNCTION hex2dec (hexval IN CHAR) RETURN NUMBER IS
  i                 NUMBER;
  digits            NUMBER;
  result            NUMBER := 0;
  current_digit     CHAR(1);
  current_digit_dec NUMBER;
BEGIN
  digits := LENGTH(hexval);
  FOR i IN 1..digits LOOP
     current_digit := SUBSTR(hexval, i, 1);
     IF current_digit IN ('A','B','C','D','E','F') THEN
        current_digit_dec := ASCII(current_digit) - ASCII('A') + 10;
     ELSE
        current_digit_dec := TO_NUMBER(current_digit);
     END IF;
     result := (result * 16) + current_digit_dec;
  END LOOP;
  RETURN result;
END hex2dec;

FUNCTION dec2hex (N IN NUMBER) RETURN VARCHAR2 IS
  hexval VARCHAR2(64);
  N2     NUMBER := N;
  digit  NUMBER;
  hexdigit  CHAR;
BEGIN
  WHILE ( N2 > 0 ) LOOP
     digit := MOD(N2, 16);
     IF digit > 9 THEN 
        hexdigit := CHR(ASCII('A') + digit - 10);
     ELSE
        hexdigit := TO_CHAR(digit);
     END IF;
     hexval := hexdigit || hexval;
     N2 := TRUNC( N2 / 16 );
  END LOOP;
  RETURN hexval;
END dec2hex;

END dbms_numsystem;
/
show errors

Count

相关实践学习
使用PolarDB和ECS搭建门户网站
本场景主要介绍基于PolarDB和ECS实现搭建门户网站。
阿里云数据库产品家族及特性
阿里云智能数据库产品团队一直致力于不断健全产品体系,提升产品性能,打磨产品功能,从而帮助客户实现更加极致的弹性能力、具备更强的扩展能力、并利用云设施进一步降低企业成本。以云原生+分布式为核心技术抓手,打造以自研的在线事务型(OLTP)数据库Polar DB和在线分析型(OLAP)数据库Analytic DB为代表的新一代企业级云原生数据库产品体系, 结合NoSQL数据库、数据库生态工具、云原生智能化数据库管控平台,为阿里巴巴经济体以及各个行业的企业客户和开发者提供从公共云到混合云再到私有云的完整解决方案,提供基于云基础设施进行数据从处理、到存储、再到计算与分析的一体化解决方案。本节课带你了解阿里云数据库产品家族及特性。
相关文章
|
1月前
|
Oracle 关系型数据库 分布式数据库
PolarDB常见问题之PolarDB(Oracle兼容版) 执行命令报错如何解决
PolarDB是阿里云推出的下一代关系型数据库,具有高性能、高可用性和弹性伸缩能力,适用于大规模数据处理场景。本汇总囊括了PolarDB使用中用户可能遭遇的一系列常见问题及解答,旨在为数据库管理员和开发者提供全面的问题指导,确保数据库平稳运行和优化使用体验。
|
1月前
|
关系型数据库 分布式数据库 数据库
PolarDB PostgreSQL版:Oracle兼容的高性能数据库
PolarDB PostgreSQL版是一款高性能的数据库,具有与Oracle兼容的特性。它采用了分布式架构,可以轻松处理大量的数据,同时还支持多种数据类型和函数,具有高可用性和可扩展性。它还提供了丰富的管理工具和性能优化功能,为企业提供了可靠的数据存储和处理解决方案。PolarDB PostgreSQL版在数据库领域具有很高的竞争力,可以满足各种企业的需求。
|
7月前
|
Oracle 关系型数据库 数据库
PostgreSQL和Oracle两种数据库有啥区别?如何选择?
PostgreSQL和Oracle两种数据库有啥区别?如何选择?
206 0
|
4月前
|
SQL Oracle 关系型数据库
Oracle,Postgresql等数据库使用
Oracle,Postgresql等数据库简单使用
133 0
Oracle,Postgresql等数据库使用
|
7月前
|
Oracle 关系型数据库 分布式数据库
如何从Oracle迁移到PolarDB(ADAM)(二)
如何从Oracle迁移到PolarDB(ADAM)(二)
128 0
|
7月前
|
SQL Oracle 关系型数据库
Polar DB-O (兼容 Oracle 语法版本)和Polar DB PostgreSQL 版本概述(二)
Polar DB-O (兼容 Oracle 语法版本)和Polar DB PostgreSQL 版本概述(二)
697 0
|
9月前
|
SQL Cloud Native 关系型数据库
ADBPG(AnalyticDB for PostgreSQL)是阿里云提供的一种云原生的大数据分析型数据库
ADBPG(AnalyticDB for PostgreSQL)是阿里云提供的一种云原生的大数据分析型数据库
739 1
|
9月前
|
数据可视化 关系型数据库 MySQL
将 PostgreSQL 迁移到 MySQL 数据库
将 PostgreSQL 迁移到 MySQL 数据库
1062 2
|
8月前
|
SQL 存储 自然语言处理
玩转阿里云RDS PostgreSQL数据库通过pg_jieba插件进行分词
在当今社交媒体的时代,人们通过各种平台分享自己的生活、观点和情感。然而,对于平台管理员和品牌经营者来说,了解用户的情感和意见变得至关重要。为了帮助他们更好地了解用户的情感倾向,我们可以使用PostgreSQL中的pg_jieba插件对这些发帖进行分词和情感分析,来构建一个社交媒体情感分析系统,系统将根据用户的发帖内容,自动判断其情感倾向是积极、消极还是中性,并将结果存储在数据库中。
玩转阿里云RDS PostgreSQL数据库通过pg_jieba插件进行分词
|
8月前
|
关系型数据库 测试技术 分布式数据库
PolarDB | PostgreSQL 高并发队列处理业务的数据库性能优化实践
在电商业务中可能涉及这样的场景, 由于有上下游关系的存在, 1、用户下单后, 上下游厂商会在自己系统中生成一笔订单记录并反馈给对方, 2、在收到反馈订单后, 本地会先缓存反馈的订单记录队列, 3、然后后台再从缓存取出订单并进行处理. 如果是高并发的处理, 因为大家都按一个顺序获取, 容易产生热点, 可能遇到取出队列遇到锁冲突瓶颈、IO扫描浪费、CPU计算浪费的瓶颈. 以及在清除已处理订单后, 索引版本未及时清理导致的回表版本判断带来的IO浪费和CPU运算浪费瓶颈等. 本文将给出“队列处理业务的数据库性能优化”优化方法和demo演示. 性能提升10到20倍.
597 4

相关产品

  • 云原生数据库 PolarDB
  • 推荐镜像

    更多