# Big bits – really long bit strings

Posted by

A while back we had an AskTom question about arbitrary length addition and subtraction, and so I whipped a small PL./SQL in this post. A similar question came in recently about converting decimals to binary, but once again for decimals of arbitrary length.

So here’s a quick piece of PL/SQL for anyone wanting really a large number of bits

```

SQL> create or replace
2  function dec_to_bit(p_decimal varchar2) return varchar2 is
3
4    l_num varchar2(4000) := p_decimal;
5    l_res varchar2(4000);
6    l_last_dig pls_integer;
7
8    function div2(p_dec varchar2) return varchar2 is
9      type   integer_array is  table of integer;
10      n1     integer_array := integer_array();
11      res    integer_array := integer_array();
12      carry  pls_integer := 0;
13      tmp    pls_integer;
14      str    varchar2(1000);
15    begin
16      for i in 1 .. length(p_dec) loop
17        n1.extend;
18        n1(i) := to_number(substr(p_dec,i,1));
19      end loop;
20      res.extend(n1.count);
21
22      for i in 1 .. n1.count
23      loop
24         str := str || trunc(((10*carry)+n1(i))/2);
25         carry := mod(n1(i),2);
26      end loop;
27      return ltrim(str,'0');
28    end;
29  begin
30    loop
31       l_last_dig := to_number(substr(l_num,-1,1));
32       l_res := to_char(mod(l_last_dig,2)) || l_res;
33       l_num := div2(l_num);
34       exit when l_num is null;
35    end loop;
36    return l_res;
37  end;
38  /

Function created.

SQL>
SQL> set serverout on
SQL> select dec_to_bit('12321231231098371928379182739182734589729384752345') bitstr from dual;

BITSTR
----------------------------------------------------------------------------------------------------------------------------------
1000011011100011011100011101111011000101010000000100000110010110101110100110110011011010000101111010101100100110010010001000110001
0000011010100110001110010011011001
```

Enjoy!

This site uses Akismet to reduce spam. Learn how your comment data is processed.