Buffer、ArrayBuffer及DataView之间的转换Buffer
是Nodejs提供的可以直接操作⼆进制数据的类
ArrayBuffer
nodejs字符串转数组 是符合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 {
[Uint8Contents]: <68 65 6c 6c 6f 2c 77 6f 72 6c 64>,
byteLength: 11
}
3. 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);
<Buffer 68 65 6c 6c 6f 2c 77 6f 72 6c 64>
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 {
[Uint8Contents]: <68 65 6c 6c 6f 2c 77 6f 72 6c 64>, byteLength: 11
}
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论