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 to Octal/Hex number in SQL

February 29th, 2008 By Frank Zhou

The following SQL pattern can be used to convert Binary to Octal or Hex number in SQL.

SQL> exec :base := 8
SQL> exec :input := '1111011'

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

SELECT regexp_replace(XMLAgg(XMLElement(X, str) ORDER BY grp desc),'<X>|</X><X>|</X>') RESULT
FROM
(SELECT substr('0123456789ABCDEF', SUM(num)+1,1) str, grp
 FROM
 (SELECT num * POWER(2,row_number() over (partition by grp order by rn)-1) num, grp
  FROM
  (SELECT doc.extract('/X/text()').getStringVal() as num, rownum rn,
          last_value(case when mod(rownum, a.base) = 1 then rownum end ignore nulls)
          over (order by rownum ) as grp
   FROM
   (SELECT ceil(sqrt(:base)) base, :input as input, length(:input) len FROM DUAL) a,
    TABLE(xmlSequence(extract(XMLType('<DOC>'||
         REGEXP_REPLACE(utl_raw.cast_to_varchar2(utl_raw.reverse(utl_raw.cast_to_raw
     (lpad(a.input, a.len +
      CASE WHEN a.base = a.base - MOD(a.len, a.base) THEN 0
                  ELSE a.base - MOD(a.len, a.base ) END
   ,'0')))),'(.)','<X>\1</X>')
  ||'</DOC>'),'/DOC/X'))) doc
  )
 )
 GROUP BY grp
);
RESULT
--------------------------------------------
173                                                                            

SQL> exec :base := 16

SQL> /

RESULT
--------------------------------------------
7B

Leave a Reply

You must be logged in to post a comment.

RSS feed for comments on this question