admin管理员组

文章数量:1335832

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??

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??

Share Improve this question edited Oct 8, 2022 at 12:59 Lee 31.1k31 gold badges123 silver badges184 bronze badges asked Jul 11, 2016 at 19:09 BanerBaner 511 silver badge9 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 4
var n = 0x20005c98;
var s = n.toString(16)

var size = Math.ceil(s.length / 2) * 2;
while (s.length < size) s = "0" + s;

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

2.6x faster version that's also easier to understand because it is explicitly doing what you asked. But it does assumes a 4 byte integer.

var n = 0x20005c98;

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

ReverseEndian(n)

I used this to time stuff:

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

You can use the endianness module:

const endianness = require('endianness')
let buf = Buffer.from('20005c98','hex')
endianness(buf ,buf.length)  //toggles endianness in place
console.log(buf,buf.toString(16)

本文标签: javascriptConverting number to big endian on Node jsStack Overflow