Create Or Replace Function To_Dec(p_Str In Varchar2, --要转换的数字(2,8,16进制)
p_From_Base In Number Default 16) --转换前的进制
Return Number Is
i_Num Number Default 0;
i_Hex Varchar2(16) Default '0123456789ABCDEF';
Begin
For i In 1 .. Length(p_Str) Loop
i_Num := i_Num * p_From_Base + Instr(i_Hex, Upper(Substr(p_Str, i, 1))) - 1;
End Loop;
Return i_Num;
End To_Dec;
2.十进制转换为其它进制(2,8,16)
Create Or Replace Function To_Base(p_Dec In Number, --要转换的数字(10进制)
p_Base In Number) --转换后的进制
Return Varchar2 Is
i_Str Varchar2(255) Default Null;
i_Num Number Default p_Dec;
i_Hex Varchar2(16) Default '0123456789ABCDEF';
Begin
If Trunc(p_Dec) <> p_Dec Or p_Dec < 0 Then
Raise Program_Error;
End If;
i_Str := Substr(i_Hex, Mod(i_Num, p_Base) + 1, 1) || i_Str;
i_Num := Trunc(i_Num / p_Base);
Exit When i_Num = 0;
End Loop;
Return i_Str;
End To_Base;
二、通过上面两个函数,可以将10进制作为转换的中间桥梁。在进行任意进制转换时,都可以先将要转换的进制转为10进 制,然后再通过10进制转换为别的进制。 通过下面函数来实现:
Create Or Replace Function Bodh_Convert(p_Str In Varchar2, --要转换的数字(2,8,10,16进制)
p_From Number, --转换前的进制
p_To Number) --转换后的进制
Return Varchar2 Is
v_Temp Number Default 0;
v_Num Varchar2(128) Default Null;
Begin
If p_From = 2 Then
If p_To = 8 Then
v_Temp := To_Dec(p_Str, p_From);
v_Num := To_Base(v_Temp, p_To);
Elsif p_To = 10 Then
v_Num := To_Dec(p_Str, p_From);
Elsif p_To = 16 Then
v_Temp := To_Dec(p_Str, p_From);
v_Num := To_Base(v_Temp, p_To);
End If;
Elsif p_From = 8 Then
If p_To = 2 Then
v_Temp := To_Dec(p_Str, p_From);
v_Num := To_Base(v_Temp, p_To);
Elsif p_To = 10 Then
v_Num := To_Dec(p_Str, p_From);
Elsif p_To = 16 Then
v_Temp := To_Dec(p_Str, p_From);
v_Num := To_Base(v_Temp, p_To);
End If;
Elsif p_From = 10 Then
If p_To = 2 Then
v_Num := To_Base(To_Number(p_Str), p_To);
Elsif p_To = 8 Then
v_Num := To_Base(To_Number(p_Str), p_To);
Elsif p_To = 16 Then
v_Num := To_Base(To_Number(p_Str), p_To);
End If;
Elsif p_From = 16 Then
If p_To = 2 Then
v_Temp := To_Dec(p_Str, p_From);
v_Num := To_Base(v_Temp, p_To);
Elsif p_To = 8 Then
v_Temp := To_Dec(p_Str, p_From);
v_Num := To_Base(v_Temp, p_To);
Elsif p_To = 10 Then
v_Num := To_Dec(p_Str, p_From);
End If;
End If;
Return v_Num;
Exception
When Others Then
Dbms_Output.Put_Line('请输入正确的参数');
End Bodh_Convert;
三、示例:
SQL> select bodh_convert('1111',2,8) from dual; --2进制转8进制
BODH_CONVERT('1111',2,8)
--------------------------------------------------------------------------------
SQL> select bodh_convert('1111',2,10) from dual; --2进制转10进制
BODH_CONVERT('1111',2,10)
--------------------------------------------------------------------------------
SQL> select bodh_convert('1111',2,16) from dual; --2进制转16进制
BODH_CONVERT('1111',2,16)
--------------------------------------------------------------------------------
广播电视节目制作经营许可证(京) 字第1234号 中国互联网协会会员