JavaScript中等同于htonl的函数?

3

对于一个AJAX请求,我需要将一个魔法数字作为请求体的前四个字节发送,最高有效字节优先,并在请求体中包含其他几个(非常量)值。在JavaScript中是否有类似于htonl的东西?

例如,给定0x42656566,我需要生成字符串“Beef”。不幸的是,我的数字大概是0xc1ba5ba9。当服务器读取请求时,它得到的值是-1014906182(而不是-1044751447)。


这可能会有所帮助:http://www.i-programmer.info/programming/javascript/2550-javascript-bit-manipulation.html - Diodeus - James MacFarlane
2个回答

4

没有内置的函数,但像这样的代码应该可以工作:

// 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);
}

那会返回一个数字数组;不幸的是,我需要一个字符串。 - Tommy McGuire
1
@TommyMcGuire 我也会添加一个如何实现的例子。 - Matthew Crumley
应该可以了,我想。当我使用那种方法将数字转换为字符串时,我可以将其转换回相同的数字。但服务器报告了不同的结果。我一定还有其他问题。 - Tommy McGuire

2
简化版 http://jsfiddle.net/eZsTp/
function dot2num(dot) { // the same as ip2long in php
    var d = dot.split('.');
    return ((+d[0]) << 24) +  
           ((+d[1]) << 16) + 
           ((+d[2]) <<  8) + 
            (+d[3]);
}

function num2array(num) {
     return [
        (num & 0xFF000000) >>> 24,
        (num & 0x00FF0000) >>> 16,   
        (num & 0x0000FF00) >>>  8,
        (num & 0x000000FF)
       ];    
}

function htonl(x)
{
     return dot2num(num2array(x).reverse().join('.')); 
}

var ipbyte = dot2num('12.34.56.78');
alert(ipbyte);
var inv = htonl(ipbyte);
alert(inv + '=' + num2array(inv).join('.'));

htonl返回一个数字,我需要一个字符串。让我在问题中添加一个示例。 - Tommy McGuire
1
@TommyMcGuire 什么样的字符串?如果你有一个原始的字符串 - alert('String'.split('').reverse().join('')); - Cheery

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接