javascript - 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()
.
解决方案
您可以使用返回数组迭代器的方法取回原始字节.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
输出是十进制的,而不是十六进制的。
推荐阅读
- arangodb - 如何在 ArangoDB 中表达 subClassOf 和 subPropertyOf?
- java - 如何在 Jenkins 上自动重新运行失败的 TestNG 测试
- regex - 加入5位数字组的正则表达式
- sql - 如果日期等于在 HTML 中选择时选择的日期,则选择记录
- css - CSS - 我可以在 Calc() 中使用对象的宽度吗?
- wordnet - 知识图谱可以处理包含介词或形容词的句子吗
- python - 从硬编码打印是可行的,但是如何从 Python 中定义的方法打印这些变量输入的值?
- c# - 将新对象传递回主窗体时遇到问题 - C# .NET
- featuretools - 如何使用 FeatureTools 通过交叉表中的特征来生成新特征?
- django - Django - Unique Together 引发错误。