英文:
Buffer.from() creates an empty buffer when being passed a single number smaller than 16
问题
以下代码
let num01 = Buffer.from(Number(1).toString(16), "hex");
console.log(num01);
let num02 = Buffer.from("02", "hex");
console.log(num02);
let num16 = Buffer.from(Number(16).toString(16), "hex");
console.log(num16);
产生以下输出:
<Buffer 01> // 如何修复这个输出为 0x01?
<Buffer 02>
<Buffer 10>
如果我输入一个小于 16 的十进制数字,上述代码的第一行无法创建带有任何值的缓冲区。如果我使用带有前导零的 `Buffer.from("02", "hex");`,那么它可以正常工作。我该如何修改第一行,以便它能够接受小于 16 的十进制数字并创建适当的缓冲区呢?
<details>
<summary>英文:</summary>
The following code
let num01 = Buffer.from(Number(1).toString(16), "hex");
console.log(num01);
let num02 = Buffer.from("02", "hex");
console.log(num02);
let num16 = Buffer.from(Number(16).toString(16), "hex");
console.log(num16);
gives the following output:
<Buffer > // how to fix this into 0x01?
<Buffer 02>
<Buffer 10>
If I input a decimal number smaller than 16, line one of the code above fails to create a buffer with any values. If I do `Buffer.from("02", "hex");` with a leading zero, then it works fine. How can I modify line one so that it will accept decimal numbers smaller than 16 a create appropriate buffers.
</details>
# 答案1
**得分**: 1
根据[Buffer文档][1],"解码不仅由十六进制字符组成的字符串时,可能会发生数据截断。"
当您创建`num01`时,提供的字符串是"1",它没有正确的十六进制编码(字符数量不是偶数),因此被截断为空。
要将参数转换为具有偶数字符的字符串,您可以使用[padStart方法][2]来用零进行填充:
```javascript
let num01 = Buffer.from(Number(1).toString(16).padStart(2, "0"), "hex");
或者处理具有任意位数的数字:
let value = Number(1).toString(16);
let num01 = Buffer.from(value.length % 2 ? "0" + value : value, "hex");
英文:
According to the docs for Buffer, "Data truncation may occur when decoding strings that do not exclusively consist of an even number of hexadecimal characters."
When you create num01
, you provide the string "1" which is not properly hex-encoded (doesn't have an even number of characters), so it's truncated to nothing.
To turn the argument into an even number of characters, you can use the padStart method to pad it with zeros:
let num01 = Buffer.from(Number(1).toString(16).padStart(2, "0"), "hex");
Or to handle numbers with any number of digits:
let value = Number(1).toString(16);
let num01 = Buffer.from(value.length % 2 ? "0" + value : value, "hex");
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论