Postgresql Convert bit varying to integer

你离开我真会死。 提交于 2019-12-02 04:15:20

问题


Searched the postgresql docs http://www.postgresql.org/docs/8.4/interactive/functions-bitstring.html for information on converting bit varying to integer

But couldnt' find any info.

select '011111'::bit(4)::varbit(4)::integer as varbit

Appreciate your response.


回答1:


One way:

SELECT b, lpad(b::text, 32, '0')::bit(32)::int
FROM (
    VALUES
     ('01'::varbit)
    ,('011111')
    ,('111')
 ) t (b);

Result:

b      | lpad
-------+------
01     |    1
011111 |   31
111    |    7

Related answer:

  • Convert hex in text representation to decimal number



回答2:


Let's say our table has 3 columns and 3 rows. We can simulate it with:

select *
from (
    values ('row1', 1::int, 12::bit(8)::varbit), 
           ('row2', 2::int, 23::bit(8)::varbit), 
           ('row3', 3::int, 34::bit(8)::varbit)
) as T(A,B,C);

As you can see, first columns is varchar , second is int and the third is varbit.

Let's convert third column to int:

select C::bit(8)::int 
from (
    values ('row1', 1::int, 12::bit(8)::varbit), 
           ('row2', 2::int, 23::bit(8)::varbit), 
           ('row3', 3::int, 34::bit(8)::varbit)
) as T(A,B,C);
==C==
  12
  23
  34

The point is, you have to convert it to bit(n) first, then you can convert bit(n) to varbit. The same thing is also true for int to varbit.



来源:https://stackoverflow.com/questions/25020950/postgresql-convert-bit-varying-to-integer

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!