JavaScript equivalent to htonl?

感情迁移 提交于 2019-12-21 19:53:29

问题


For an AJAX request, I need to send a magic number as the first four bytes of the request body, most significant byte first, along with several other (non-constant) values in the request body. Is there something equivalent to htonl in JavaScript?

For example, given 0x42656566, I need to produce the string "Beef". Unfortunately, my number is along the lines of 0xc1ba5ba9. When the server reads the request, it is getting the value -1014906182 (instead of -1044751447).


回答1:


There's no built-in function, but something like this should work:

// 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,
    ];
}

To get the bytes as a string, just call String.fromCharCode on each byte and concatenate them:

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



回答2:


Simplified version 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('.'));


来源:https://stackoverflow.com/questions/9283093/javascript-equivalent-to-htonl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!