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??
3 Answers
Reset to default 4var 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
版权声明:本文标题:javascript - Converting number to big endian on Node js - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742400266a2467745.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论