对于 AJAX 请求,我需要发送一个幻数作为请求正文的前四个字节,首先是最高有效字节,以及请求正文中的其他几个(非常量)值。 JavaScript 中是否有相当于 htonl 的东西?
例如,给定 0x42656566,我需要生成字符串“Beef”。不幸的是,我的号码是 0xc1ba5ba9。当服务器读取请求时,它得到的值是-1014906182(而不是-1044751447)。
没有内置函数,但类似这样的函数应该可以工作:
// Convert an integer to an array of "bytes" in network/big-endian order.
function htonl(n)
{
// Mask off 8 bytes at a time then shift them into place
return [
(n & 0xFF000000) >>> 24,
(n & 0x00FF0000) >>> 16,
(n & 0x0000FF00) >>> 8,
(n & 0x000000FF) >>> 0,
];
}
要获取字符串形式的字节,只需调用String.fromCharCode
在每个字节上并将它们连接起来:
// Convert an integer to a string made up of the bytes in network/big-endian order.
function htonl(n)
{
// Mask off 8 bytes at a time then shift them into place
return String.fromCharCode((n & 0xFF000000) >>> 24) +
String.fromCharCode((n & 0x00FF0000) >>> 16) +
String.fromCharCode((n & 0x0000FF00) >>> 8) +
String.fromCharCode((n & 0x000000FF) >>> 0);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)