Buffer.from() 在传入小于 16 的单个数字时创建一个空缓冲区

huangapple go评论60阅读模式
英文:

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(&quot;02&quot;, &quot;hex&quot;);` 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, &quot;0&quot;), &quot;hex&quot;);

Or to handle numbers with any number of digits:

let value = Number(1).toString(16);
let num01 = Buffer.from(value.length % 2 ? &quot;0&quot; + value : value, &quot;hex&quot;);

huangapple
  • 本文由 发表于 2023年5月13日 21:25:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/76242961.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定