IP地址與十進制相互轉換

一、IP 轉成10進制spa

function ipToInt(ip){
    var REG =/^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/;
    var xH = "",result = REG.exec(ip);
    if(!result) return -1;
    return (parseInt(result[1]) << 24 
        | parseInt(result[2]) << 16
        | parseInt(result[3]) << 8
        | parseInt(result[4]))>>>0;
}

例:code

ipToInt("172.18.0.2");  // 2886860802

 

二、10進制轉成 IPorm

function intToIp(INT){
    if(INT < 0 || INT > 0xFFFFFFFF){
        throw ("The number is not normal!");
    }
    return (INT>>>24) + "." + (INT>>16 & 0xFF) + "." + (INT>>8 & 0xFF) + "." + (INT & 0xFF);
}

例:blog

intToIp(2886860802); // 172.18.0.2
相關文章
相關標籤/搜索