js的网络序转换

js没有原生的网络序和主机序的转换接口。但是随着nodejs的火,也开始有这个包了https://npmjs.org/package/network-byte-order‎

/*** Convert a 32-bit quantity (long integer) from host byte order to network byte order (Little-Endian to Big-Endian).** @param {Array|Buffer} b Array of octets or a nodejs Buffer* @param {number} i Zero-based index at which to write into b* @param {number} v Value to convert*/exports.htonl = function(b, i, v) {b[i] = (0xff & (v >> 24));b[i + 1] = (0xff & (v >> 16));b[i + 2] = (0xff & (v >> 8));b[i + 3] = (0xff & (v));};/*** Convert a 32-bit quantity (long integer) from network byte order to host byte order (Big-Endian to Little-Endian).** @param {Array|Buffer} b Array of octets or a nodejs Buffer to read value from* @param {number} i Zero-based index at which to read from b* @returns {number}*/exports.ntohl = function(b, i) {return ((0xff & b[i]) << 24) |((0xff & b[i + 1]) << 16) |((0xff & b[i + 2]) << 8) |((0xff & b[i + 3]));};

稍微封装下就能放到js中使用了。

function onH2NS() {var n = document.getElementById("xxx").value;v = parseInt(n);var b = new Array();b[0] = (0xff & (v >> 8));b[1] = (0xff & (v));data = (b[0] + (b[1] << 8)) >>> 0;document.getElementById("yyy").innerHTML = "htons(" + n + ") = " + data.toString();}function onN2HL() {var n = document.getElementById("xxx").value;v = parseInt(n);data = (((0xff & v) << 24) |                ((0xff & (v >> 8)) << 16) |                ((0xff & (v >> 16)) << 8) |                ((0xff & (v >> 24)))) >>> 0;document.getElementById("yyy").innerHTML = "ntohl(" + n + ") = " + data.toString();}

原创文章,转载请注明转载自下雨天本文链接地址js的网络序转换

QR:  js的网络序转换

阅读全文