【PL/SQL】IP與數字互轉

--查看過程、函數視圖sql

dba_source user_source all_sourceide

--刪除存儲過程函數

drop procedure SP_TMP;oop

drop function fun_tmp;server


---函數ip

to_char:轉換數據這字符串,也能夠把10進制轉換爲16進制(注意xx的個數)。字符串

SQL> select to_char(100,'xx') from dual;

TO_
---
 64


to_number:字符串轉爲數字,也能夠16進制轉爲10進制。it

SQL> select to_number('1f','xx') from dual;

TO_NUMBER('1F','XX')
--------------------
                  31



substr:從字符串截取字符。能夠從0或1開始,結果同樣。io

SQL> select substr('abcdefg',1,2) from dual;

SU
--
ab

SQL> select substr('abcdefg',0,2) from dual;

SU
--
ab



--------------------------------------------------------------------
--ip轉換爲數字函數
--------------------------------------------------------------------
create or replace function fun_ipconvernum(v_ip in varchar2)
return number
as
  v_tmp varchar2(2);
  v_all varchar2(8);
  v_tow varchar2(3);
  v_chkn number;
  v_chkt number;
begin
  v_tmp:='';v_chkn:=0;v_chkt:=1;v_all:='';
  for i in 1..3 loop
    v_chkn:=instr(v_ip,'.',v_chkn+1);
    v_tow:=substr(v_ip,v_chkt,v_chkn-v_chkt);
    v_tmp:=trim(to_char(v_tow,'xx'));
    if length(v_tmp)=1 then
      v_all:=v_all || lpad(v_tmp,2,'0');
    else
      v_all:=v_all || v_tmp;
    end if;
    v_chkt:=v_chkn+1;
    if i=3 then
      v_tow:=substr(v_ip,v_chkt,length(v_ip)-v_chkn);
      v_tmp:=trim(to_char(v_tow,'xx'));
      if length(v_tmp)=1 then
        v_all:=v_all || lpad(v_tmp,2,'0');
      else
        v_all:=v_all || v_tmp;
      end if;
    end if;
  end loop;
      --dbms_output.put_line(v_all);
      return to_number(v_all,'xxxxxxxxxx');
end;
-------------------------
set serveroutput on
exec sp_ipconvernum('192.168.8.4')
select fun_ipconvernum('255.255.255.255') from dual;

--------------------------------------------------------------------
--數字轉換爲ip函數
--------------------------------------------------------------------
create or replace function fun_numconverip(v_nip number)
return varchar2
as 
v_ip varchar2(32);
v_iphex varchar2(8);
begin
  v_ip:='';
  v_iphex:=trim(to_char(v_nip,'xxxxxxxxxx'));
  for i in 1..4 loop
    if i=4 then
      v_ip:=v_ip||to_number(substr(v_iphex,(i-1)*2+1,2),'xxx');
    else
      v_ip:=v_ip||to_number(substr(v_iphex,(i-1)*2+1,2),'xxx')||'.';
    end if;
  end loop;
  return v_ip;
end;


-----------------------------------------------------------------
select fun_numconverip(3232237572) from dual;
-----------------------------------------------------------------
相關文章
相關標籤/搜索