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.
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");