17/10/2017

[PL/SQL] Convert number to binary string

Here is a simple function to convert a number to a binary string in Oracle PLSQL. This can also easily be converted to an number array instead.

 function num_to_bin(   
  n number   
  )   
  return varchar2   
  is   
  binval varchar2(64);   
  n2  number := n;   
  begin  
  if (n == 0) then  
   return '0';  
  end if;   
  while (n2 > 0) loop   
   binval := mod(n2, 2) || binval;   
   n2  := trunc(n2 / 2);   
  end loop;   
     
  return binval;   
  end num_to_bin;   

2 comments:

  1. Hello,
    nice one thanks.
    I have added something so it returns '0' instead of null when n = 0.

    ReplyDelete
    Replies
    1. Thanks, I updated the code so it works for everyone. Cheers

      Delete

With great power comes great responsibility