相当于htonl的JavaScript? [英] JavaScript equivalent to htonl?

查看:111
本文介绍了相当于htonl的JavaScript?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于AJAX请求,我需要发送一个幻数作为请求正文的前四个字节(最高有效字节在前)以及请求正文中的其他几个(非常数)值.在JavaScript中是否有等同于htonl的东西?

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?

例如,给定0x42656566,我需要产生字符串"Beef".不幸的是,我的电话号码是0xc1ba5ba9.服务器读取请求时,将获得值-1014906182(而不是-1044751447).

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).

推荐答案

没有内置函数,但是类似的东西应该可以工作:

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

要获取字节作为字符串,只需在每个字节上调用String.fromCharCode并将它们连接起来即可:

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

这篇关于相当于htonl的JavaScript?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆