I have this very simple code written in javascript.
let str = "Hello World";
console.log(Buffer.from(str,"utf-8"));
result: <Buffer 48 65 6c 6c 6f 20 57 6f 72 6c 64>
How can i get the bytes from the Buffer? So result will look like this
expected result 48656c6c6f20576f726c64
CodePudding user response:
Node's Buffer
includes a toString
method for this purpose. You can supply the desired encoding format as the first argument. In your case, you can use "hex"
meaning hexadecimal:
const str = 'Hello World';
const buf = Buffer.from(str, 'utf-8');
const hex = buf.toString('hex');
console.log(hex === '48656c6c6f20576f726c64'); // true
CodePudding user response:
Basically you iterate the values since Buffer
has that method and more. It's quite array-like. Use toString(16)
to convert to hex.
let str = "Hello World";
var buf = Buffer.from(str, "utf-8");
var result = [];
buf.forEach(function(value) {
result.push(value.toString(16))
})
console.log(result.join(""));