Binary

From Oracle FAQ
Jump to: navigation, search

Binary is a numbering system with only two digit values: 0 (zero) and 1 (one). These digits are called bits.

[edit] Conversion functions

Use the following conversion PL/SQL functions to convert binary values to decimal and vice versa:

CREATE OR REPLACE FUNCTION bin2dec (binval in char) RETURN number IS
  i                 number;
  digits            number;
  result            number := 0;
  current_digit     char(1);
  current_digit_dec number;
BEGIN
  digits := length(binval);
  for i in 1..digits loop
     current_digit := SUBSTR(binval, i, 1);
     current_digit_dec := to_number(current_digit);
     result := (result * 2) + current_digit_dec;
  end loop;
  return result;
END bin2dec;
/
 
SQL> SELECT bin2dec('10110') FROM dual;
BIN2DEC('10110')
----------------
              22
CREATE OR REPLACE FUNCTION dec2bin (N in number) RETURN varchar2 IS
  binval varchar2(64);
  N2     number := N;
BEGIN
  while ( N2 > 0 ) loop
     binval := mod(N2, 2) || binval;
     N2 := trunc( N2 / 2 );
  end loop;
  return binval;
END dec2bin;
/

SQL> SELECT dec2bin(22) FROM dual;
DEC2BIN(22)
----------------
10110

[edit] Conversion

Simple decimal to binary conversion table:

Decimal Binary
0 0000 0000
1 0000 0001
2 0000 0010
3 0000 0011
4 0000 0100
5 0000 0101
6 0000 0110
7 0000 0111
8 0000 1000
9 0000 1001
10 0000 1010

[edit] Also see

  • bit - Oracle bit-operator functions
  • Octal - numbering system with 8 digits
  • Hexadecimal - numbering system with 16 digits
Glossary of Terms
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z #