如何使用Oracle PL / SQL将字节转换为ASCII字符

时间:2017-01-28 20:13:35

标签: sql oracle plsql

我将这个字节转换为ASCII字符有问题,需要使用Oracle PL / SQL进行类似的转换,原来的是在MS SQLserver中:  

   /// </summary> 

/// <param name="blob"></param>

/// <returns></returns> 

[Microsoft.SqlServer.Server.SqlFunction(IsDeterministic = true, IsPrecise = true)] 

public static String VarbinaryToVarchar(SqlBytes blob) 
{ 
    if (blob.IsNull) return null; 

    byte[] buffer = blob.Buffer; 
    char[] res = new char[buffer.Length * 2]; 
    for (int i = 0; i < buffer.Length; i++) 
    { 
        res[i * 2] = (char)((buffer[i] & 0xF) + 65); 
        res[i * 2 + 1] = (char)(((buffer[i] >> 4) & 0xF) + 65); 
    } 
    return new String(res); 
} 

先谢谢你们!

1 个答案:

答案 0 :(得分:0)

您可以探索使用Oracle内置UTL_RAWHEXTORAW,然后转换您的十六进制。值为整数并添加“65”。之后,CHR将为您提供您期望的ASCII

 declare
   p_s_in varchar2(1000):= '0000EB862CB8024892CD419A26BB3AE';
   l_s_cmp varchar2(1000):= 'AAAALOGIMCILCAIEJNBEKJGCLIDLOK';
   l_s_out varchar2(1000) :='';
   p_pad binary_integer:=1;
   l_cur1 char;
   l_cur2 char;
   l_cur_bi1 binary_integer;
   l_cur_bi2 binary_integer;
 begin

   l_cur1 := substr(p_s_in, 1,1);
   l_cur2 := substr(p_s_in, 2, 1);
   while (length(l_cur1)=1)
   loop
     l_cur_bi1 := UTL_RAW.cast_to_binary_integer(HEXTORAW(l_cur1))+65;
     l_cur_bi2 := UTL_RAW.cast_to_binary_integer(HEXTORAW(l_cur2))+65;

     dbms_output.put_line(l_cur2||'->'||chr(l_cur_bi2)||'?>'||substr(l_s_cmp, 1,1));
     l_s_cmp := substr(l_s_cmp, 2);

     dbms_output.put_line(l_cur1||'->'||chr(l_cur_bi1)||'?>'||substr(l_s_cmp, 1,1));
     l_s_out:=l_s_out||chr(l_cur_bi2)||chr(l_cur_bi1);
     -- end loop
     p_s_in := substr(p_s_in, 3);
     l_s_cmp := substr(l_s_cmp, 2);
     l_cur1 := substr(p_s_in, 1, 1);
     l_cur2 := substr(p_s_in, 2, 1);
   end loop;
   dbms_output.put_line(l_s_out);
 end;
 /

我让调试输出,因为我不完全确定这是你正在寻找的。您给我们的输出与我的代码略有不同: enter image description here ......你或我可能会遗漏一些东西。