How to convert ASCII strings and hexadecimal strings in Oracle

Source: Internet
Author: User

ASCII string ==> hexadecimal string

Create or replace function asctohex (sin in varchar2)
Return varchar2
Is
Stmp varchar2 (4000 );
I integer;
Begin
I: = 1;
Stmp: = '';
For I in 1 .. length (SIN) loop
Stmp: = stmp | trim (to_char (ASCII (substr (sin, I, 1), 'xxx '));
End loop;
Return stmp;
End;
/

Hexadecimal string ==> ASCII string
To distinguish character sets, take Chinese characters as an example. For database character sets that are Chinese, make sure they can be correctly converted back.

The database character set is Chinese.

Create or replace function hextoasc (sin in varchar2)
Return varchar2
Is
Stmp varchar2 (4000 );
I integer;
X integer;
Begin
I: = 1;
Stmp: = '';
Loop
Exit when I> length (SIN );
X: = to_number (substr (sin, I, 2), 'xxxx ');
If X> 128 then
Stmp: = stmp | CHR (to_number (substr (sin, I, 4), 'xxx '));
I: = I + 4;
Else
Stmp: = stmp | CHR (to_number (substr (sin, I, 2), 'xxx '));
I: = I + 2;
End if;

End loop;
Return stmp;
End;
/

The database character set is English

Create or replace function hextoasc (sin in varchar2)
Return varchar2
Is
Stmp varchar2 (4000 );
I integer;
Begin
I: = 1;
Stmp: = '';
Loop
Exit when I> length (SIN );
Stmp: = stmp | CHR (to_number (substr (sin, I, 2), 'xxx '));
I: = I + 2;
End loop;
Return stmp;
End;
/

The test is as follows:

SQL> select hextoasc (asctohex ('Hello ABC? ') from dual;
Hextoasc (asctohex ('Hello ABC '))
--------------------------------------------------------------------------------
Hello, ABC?

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.