Buffer、ArrayBuffer及DataView之间的转换
Buffer
是Nodejs提供的可以直接操作二进制数据的类
ArrayBuffer
是符合ES标准的
用来表示通用的、固定长度的原始二进制数据缓冲区,是一个字节数组,可读但不可直接写
注:
ArrayBuffer对象并没有提供任何读写内存的方法,但允许在其上方建立DataView,从而插入与读取内存中的数据
DataView
是一个可以从 ArrayBuffer 对象中读写多种数值类型的底层接口
类型有
Int8Array:8位有符号整数,长度1个字节
Uint8Array:8位无符号整数,长度1个字节
Int16Array:16位有符号整数,长度2个字节
Uint16Array:16位无符号整数,长度2个字节
Int32Array:32位有符号整数,长度4个字节
Uint32Array:32位无符号整数,长度4个字节
Float32Array:32位浮点数,长度4个字节
Float64Array:64位浮点数,长度8个字节
1.buffer 转 Uint8Array
var buffer = Buffer.from('hello,world');
var arraybuffer = new Uint8Array(buffer);
console.log(arraybuffer);
Uint8Array(11) [
104, 101, 108, 108,
111, 44, 119, 111,
114, 108, 100
]
2.Uint8Array 转 ArrayBuffer
var buffer = Buffer.from('hello,world');
var array = new Uint8Array(buffer);
var arraybuffer = array.buffer;
console.log(arraybuffer);
ArrayBuffer {
byteLength: 11
}
- ArrayBuffer转 Buffer
var buffer = Buffer.from('hello,world');
var array = new Uint8Array(buffer);
var arraybuffer = array.buffer;
var buffer1 = Buffer.from(arraybuffer);
console.log(buffer1);
4.ArrayBuffer转 DataView
var buffer = Buffer.from('hello,world');
var array = new Uint8Array(buffer);
var arraybuffer = array.buffer;
var view = new DataView(arraybuffer);
console.log(view);
5.DataView转ArrrayBuffer
var buffer = Buffer.from('hello,world');
var array = new Uint8Array(buffer);
var arraybuffer = array.buffer;
var view = new DataView(arraybuffer);
var buffer1 = view.buffer;
console.log(buffer1);
ArrayBuffer {
byteLength: 11
}