Converting number to big endian on Node js

时间:2016-07-11 19:09:08

标签: node.js

I have a user type in addresses such as 0x20005c98, which i am calling in POST method using req.body.var. However, I need this number in little endian so it shows 0x985c0020. Does anyone know how to convert this number to little endian in node js? Is there an easy way of doing this?? The network-byte-order npm is an option??

2 个答案:

答案 0 :(得分:1)

var n = 0x20005c98;
var s = n.toString(16).match(/.{1,2}/g);
s.push("0x");
s.reverse().join("").toString(16); // ==> "0x985c0020" (= 2556166176)

答案 1 :(得分:0)

2.6倍更快的版本,也更容易理解,因为它明确地做你所要求的。但它确实假设一个4字节的整数。

var n = 0x20005c98;

function ReverseEndian(x) {
    buf = Buffer.allocUnsafe(4)
    buf.writeUIntLE(x, 0, 4)
    return buf.readUIntBE(0, 4)
}

ReverseEndian(n)

我用它来计算时间:

function timeit(n, x, args) {
    console.time("xxx")
    for (i=0;i<n;++i) {
        x.apply(null, args)
        }
    console.timeEnd("xxx")
}