JavaScript相当于htonl?

时间:2012-02-14 19:36:46

标签: javascript network-programming endianness

对于AJAX请求,我需要发送一个幻数作为请求体的前四个字节,首先是最重要的字节,以及请求体中的其他几个(非常量)值。在JavaScript中是否有类似于htonl的东西?

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

2 个答案:

答案 0 :(得分:3)

没有内置功能,但这样的功能应该有效:

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

答案 1 :(得分:1)

简化版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('.'));