Converting an array from string 0 and 1 to base36

That's what. I have an array of 0 and 1. It is assumed that this is a binary string. I need to format it into a string containing the base36 conversion from this binary. In other words, I need to do this: an array of 1 and 0 β†’ some binary number β†’ convert to base36 a number β†’ put it in a string. How to do it?

Thousands of oil, 300 steels and +1 luck for the defendants.

+3
source share
1 answer

There is no built-in Oracle for such a conversion. In the following example, I use two functions prescribed by the invaluable Mr. Kyte . to_dec()turns other bases into decimal numbers, and to_base()turns decimal numbers into other bases.

The procedure takes an array of ones and zeros and returns a base string of 36.

create or replace type binary_nt as table of number(1,0);
/

create or replace function base2_to_base36 
    (p_onesnzeroes in binary_nt)
    return varchar2
is
    s_b2 varchar2(38);
    n_b10 pls_integer;
    s_b36 varchar2(38);
begin
    for i in 1..p_onesnzeroes.count()
    loop
        s_b2 := s_b2||trim(to_char(p_onesnzeroes(i)));
    end loop;

    n_b10 := to_dec(s_b2, 2);
    s_b36 := to_base(n_b10, 36);

    return s_b36;
end;
/

Proof of pudding and all that ...

SQL> set serveroutput on size unlimited
SQL>     declare
  2          bins binary_nt := binary_nt(1,0,0,0,1,1,1,0);
  3          s varchar2(128);
  4      begin
  5          --  10001110 => 142  => 3Y
  6          s :=  base2_to_base36(bins);
  7          dbms_output.put_line(s);
  8      end;
  9      /
3Y

PL/SQL procedure successfully completed.

SQL>

change

While I was collecting this sample, you posted that your array of zeros was ~ 450 entries. This procedure will not handle anything like this. He will throw ORA-01426: numeric overflowbefore you click on this size.

change 2

, NUMBER BINARY_DOUBLE ( , Tom). . array_count=470, 36:

EKQA1EJ6QB4SC8WOOWKWGGOS4KWWWWCS4WCW4SCWCOSOOS888K4CSC8SWO8OCKC8SSCWCOGK844CKG00SOW8KGS0CC4
+1

Source: https://habr.com/ru/post/1745110/


All Articles