How to convert a buffer in an array?
Buffer (Hex values):
myBuffer = <Buffer 48 65 6c 6c 6F >
I want aa variable type array like this:
myArray = [48, 65, 6c, 6c, 6F] // Hex values
or
myArray = [72, 101, 108, 108, 111] // Decimal values
IMPORTANT : I don't want to use a for
loop to traverse byte to byte of the buffer. I want to know if there is a native way to convert Buffer to Array.
Looks like you are referring to Node.js Buffer. If this is the case, you can simply do this:
var buf = new Buffer([72,101,108,108,111]) //<Buffer 48 65 6c 6c 6f>
var arr = Array.prototype.slice.call(buf) //[72,101,108,108,111]
If you're talking about arraybuffer, try this method:
function ab2str(buf) {
return String.fromCharCode.apply(null, new Uint16Array(buf));
}
If you're talking about nodejs buffer object, try this:
let bufferOne = Buffer.from('This is a buffer example.');
console.log(bufferOne);
// Output: <Buffer 54 68 69 73 20 69 73 20 61 20 62 75 66 66 65 72 20 65 78 61 6d 70 6c 65 2e>
let json = JSON.stringify(bufferOne);
console.log(json);
// Output: {"type":"Buffer","data": [84,104,105,115,32,105,115,32,97,32,98,117,102,102,101,114,32,101,120,97,109,112,108,101,46]}
json = JSON.parse(json);
json.data.forEach(e=> console.log(e.toString(16)));
// Output: 54 68 69 73 20 69 73 20 61 20 62 75 66 66 65 72 20 65 78 61 6d 70 6c 65 2e
In ES6, this would also work:
const buffer = new Buffer([72,101,108,108,111])
const arr = [...buffer] //[72,101,108,108,111]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.