OraQA

Oracle Question and Answer


Latest Comments

  • Laurent Schneider:
    if you like a Base64 format, maybe this… select utl_raw.cast_to_varchar 2(...

  • hsafra:
    You need to give more specs for the question: What letter are acceptable? What letters aren’t? Do you...

  • ragunathansd:
    I am not inserting sequence numbers from database. I need to populate the data in a grid. If a user...

  • gamyers:
    “redo log file gets full” That is the nature of a redo log file. It gets full, switched and...

Comments RSS feed


  • Do you have a solution to a problem? Do you have an unanswered question? Login and share it with the Oracle community. More...

Oracle News


Entries RSS feed

Comments RSS feed

How to convert Binary/Octal/Hex to Decimal number in SQL

February 29th, 2008 By Frank Zhou

The following SQL pattern can be used to convert Binary, Octal , Hex to Decimal (base ten) number in SQL.

SQL> variable input varchar2(28)
SQL> variable base number
SQL> exec :base := 2
SQL> exec :input := '1111011'

————————–SQL Solution ———————————-

SELECT SUM( num * POWER(base, rn -1) ) result
FROM
(SELECT instr(num_str, upper(doc.extract('/X/text()').getStringVal()))-1 as num, rownum rn, a.base
 FROM
 (SELECT '0123456789ABCDEF' as num_str, :base as base, :input as input FROM DUAL) a,
  TABLE(xmlSequence(extract(XMLType('<DOC>'||
  REGEXP_REPLACE(utl_raw.cast_to_varchar2(utl_raw.reverse(utl_raw.cast_to_raw(a.input)))
  ,'(.)','<X>\1</X>')||'</DOC>'),'/DOC/X'))) doc
);
    RESULT
----------
       123
SQL> exec :base := 8
SQL> exec :input := '173'
SQL> /    

    RESULT
----------
       123                                                                         

SQL> exec :base := 16
SQL> exec :input := '7B'    

SQL> /    

    RESULT
----------
       123
 
----------------Simple Solution for convert Hex to Decimal only-------------------- 
SQL> exec :input := '7B'   
SELECT  to_number( :input , 'xxxx' ) result FROM dual;
    RESULT
----------
       123

Leave a Reply

You must be logged in to post a comment.

RSS feed for comments on this question