首页 > 解决方案 > JS 中是否有类似 Python 中的 int.to_bytes() 这样的函数?

问题描述

我在 Stack Overflow 上的某个地方发现我们可以int.from_bytes() 通过以下方式在 Node.js 中实现功能:

const buf = Buffer.from([0x12, 0x34, 0x56, 0x78]) // 0x12345678 = 305419896
console.log(buf.readUInt32BE(0)) // 305419896

有什么替代品 int.to_bytes()吗?我想先使用int.from_bytes(),然后需要做一些操作,然后再次想使用int.to_bytes().

标签: javascriptpythonnode.js

解决方案


您可以使用返回数组迭代器的方法取回原始字节.values(),因此它可以与扩展运算符一起使用,或者Array.from如果您需要:

const buf = Buffer.from([0x12, 0x34, 0x56, 0x78]) // 0x12345678 = 305419896
console.log(buf.readUInt32BE(0)) // 305419896

console.log(...buf)
// 18 52 86 120

const arr = Array.from(buf)
console.log(arr)
// [18, 52, 86, 120]

请注意,console.log输出是十进制的,而不是十六进制的。


推荐阅读