3

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.

2 Answers 2

8

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:

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks but my intention was that I have a column of type bit varying and I wanted to convert it to integer
@Pals: The cast ::bit(32) was missing in my first draft. Fixed and added a demo.
It is working only for 32 bits. What is the solution if I have more than 32 bits?
@Pals: How would you convert that to a 4-byte integer, which cannot hold more than 32 bit of information? You did ask for integer. The next step is bigint with 64 bit.
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.