node.js 小端十六进制的十进制互转以及十六进制大小端转换

十进制 转 小端十六进制

function decToHex(num) {
    return (num + 2 ** 32).toString(16).match(/\B../g).reverse().join ``;
}

console.log(decToHex(300));
console.log(decToHex(30));
console.log(decToHex(230));

输出:
2c010000
1e000000
e6000000

小端十六进制 转 十进制

function hexToDec(num) {
    return Buffer.from(num, 'hex').readInt32LE()
}

console.log(hexToDec('2c010000'));
console.log(hexToDec('1e000000'));
console.log(hexToDec('e6000000'));

输出:
300
30
230

十六进制大小端转换

function endianConv(num) {
    return num.toString('hex').match(/.{2}/g).reverse().join("")
}

console.log(endianConv('2c010000'));
console.log(endianConv('1e000000'));
console.log(endianConv('e6000000'));

console.log(endianConv('0000012c'));
console.log(endianConv('0000001e'));
console.log(endianConv('000000e6'));

输出:
0000012c
0000001e
000000e6
2c010000
1e000000
e6000000

posted @ 2021-06-02 11:21  fengyujia  阅读(1957)  评论(0编辑  收藏  举报