常用於通訊TCP或UDP傳輸使用,本擴充檔可以輕易將Hex與Hex String互相轉換,讓您可以輕鬆判斷處理

hextool.js
    module.exports = {
        //IPv4 Hex String 轉換成 IPv4 String
        //example:c0a80101 轉換成 192.168.1.1
        hexstrip2str:function(_hexstr){
            //hextool.hexstrip2str
            var ip_n1 = parseInt(_hexstr.substring(0,2), 16);
            var ip_n2 = parseInt(_hexstr.substring(2,4), 16);
            var ip_n3 = parseInt(_hexstr.substring(4,6), 16);
            var ip_n4 = parseInt(_hexstr.substring(6,8), 16);
            return ip_n1+'.'+ip_n2+'.'+ip_n3+'.'+ip_n4;
        },
        //IPv4 String 轉換成 IPv4 Hex String
        //example:192.168.1.1 轉換成 c0a80101
        strip2hexstr:function(_str){
            //hextool.strip2hexstr
            var va = _str.split('.');
            i1 = module.exports.int2hexstr(parseInt(va[0]), 2);
            i2 = module.exports.int2hexstr(parseInt(va[1]), 2);
            i3 = module.exports.int2hexstr(parseInt(va[2]), 2);
            i4 = module.exports.int2hexstr(parseInt(va[3]), 2);
            return i1+i2+i3+i4;
        },

        //PORT(1~65535)
        hexstrport2int:function(_hexstr){
            //hextool.hexstrport2int
            return parseInt(_hexstr, 16);
        },
        intport2hexstr:function(_int){
            //hextool.intport2hexstr
            return module.exports.int2hexstr(_int, 4);
        },

        //INT
        int2hexstr:function(_int, _len){
            var _zero = typeof _len !== 'undefined' ? (_len) : _int.toString().length;
            var _zero_str = "";
            for(i=0;i<_zero;i++){
                _zero_str += "0";
            }
            var _hexstr = Number(_int).toString(16);
            _hexstr = _zero_str.substr(0, _zero - _hexstr.length) + _hexstr; 
            return _hexstr;
        },

        //HEX CONVERT
        hexstr2hex:function(_hexstr){
            return new Buffer(_hexstr.toString('hex'), 'hex');
        },
        hex2hexstr:function(_hex){
            _hex_source = new Buffer(_hex, 'utf8');
            return _hex_source.toString('hex');
        }
    };
	

酷米 © All Rights Reserved.

loading
Loading...