Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Bit String To Array in PostgreSQL

I have a 160 chars bit string and I need to have an integer array that stores the position of the bits that have a value of 1.

Example:

bitstring = '00110101'
array = [3,4,6,8]

Is it possible to do this just with SQL or do I need to define a PL/SQL function or something like that?

like image 430
Topo Avatar asked Dec 26 '22 04:12

Topo


1 Answers

It's assuredly possible to write it in SQL. Here's a starting point:

select array(
  select substring(str from i for 1) as bit
  from generate_series(1, length(str)) as i
  where bit = '1'
);

You might want to wrap that in a pl/sql function regardless, though, so to avoid duplicating code all over the place.


Working function:

create or replace function get_bit_positions(varbit) returns bit[] as $$
select array(
  select substring($1 from i for 1) as bit
  from generate_series(1, length($1)) as i
  where substring($1 from i for 1) = '1'
);
$$ language sql immutable;
like image 111
Denis de Bernardy Avatar answered Jan 09 '23 01:01

Denis de Bernardy