node 第四章 二进制数据与buffer模块

1、二进制数据 

计算机内数据都是二进制的方式存放
assic编码 'A'-->65数据,比如把数据当字符,那就是A,当数据是65;
int8/UInt8 一个字节的整数;
Int16/UInt16 二个字节整数;

Int32/UInt32 四个字节整数;

int/Uint 8个字节的整数;
Float 4个字节的小数,Double 8个字节的小数;

2、大尾与小尾

1、4个字节的数据,存到内存的4个字节;

     小尾:LE高位的数据--》高地址字节地方;--》“高高低低”

     大尾:BE高位的数据--》低地址字节的地方


3、Buffer

1、ndoe.js使用Buffer对象存放二进制数据;

2、为了快速分配,小内存会建立一个bufferpool 内存池,从内存池先获取,分配不成功超过大小再从内存申请空间

//1、给定一个大小
//2、会给这些内存一个初值,那么这个初值就是0;
var buf = Buffer.alloc(10,0xff);
console.log(buf);

//(1)给定内存分配一个给定大小的buffer的内存
//(2)allocUnsafe 不会对这些内存区赋初值,随机值,它原来是什么就是什么

buf = Buffer.allocUnsafe(10);
console.log(buf);


//allocUnsafeSlow  不从Buffer换从曲里面分配,直接从操作系统分配
//Slow 指的是没有从缓冲池里面高效的分配
//UnSafe,值得是内存没有被初始化

buf = Buffer.allocUnsafeSlow(10);
console.log(buf);

//buffer已经分配再也不能改变
console.log(buf.length);


//为了方便创建方式,复制
//分配一个buffer对象,用来存放这个字符创的二进制
// from 对象 array ,buf , string
buf = Buffer.from("hello");
console.log(buf);

buf = Buffer.from([12,13,14,56,-1,-2,-55,55]);
console.log(buf);

var buf2 = Buffer.from(buf);
console.log(buf2);

//buf[index]  index = [0 ,len-1]
//注意越界
console.log(buf[0],buf[1]);

//以大尾的形式存放 4个字节的整数
//0x00 00 ff ff ---->65535

buf.writeInt32BE(65535,0);
console.log(buf);


//小尾
buf.writeInt32LE(65535,0);
console.log(buf);

var value = buf.readInt32LE(0);
console.log(value);

//
//Buffer.bytelength
var len = Buffer.byteLength(buf2);
console.log(len);

// 4个字节的Int为例 4 * 4 = 16;
// 0, 1, 2, 3,| 4, 5, 6, 7, |8, 9, 10, 11, |12, 13, 14, 15
buf = Buffer.alloc(4 * 4);
buf.writeInt32LE(65535, 0);
buf.writeInt32LE(65535, 4);
buf.writeInt32LE(65535, 8);
buf.writeInt32LE(65535, 12);
console.log(buf);
buf.swap32();
// 3, 2, 1, 0,| 7, 6, 5, 4, |11, 10, 9, 8, |15, 14, 13, 12
console.log(buf);

console.log(buf.readInt32BE(0));
console.log(buf.readInt32BE(4));
console.log(buf.readInt32BE(8));
console.log(buf.readInt32BE(12));
console.log("++++++++++++++++++++++++++++++");

for(var v of buf.values()) {
    console.log(v);
}

// 二进制 根据特定的编码来转字符串
console.log(buf.toString('utf8'));
// "0000ffff0000ffff0000ffff0000ffff"
console.log(buf.toString('hex'));

console.log(buf.toJSON());

buf.fill('A');
console.log(buf);
console.log(buf.toString('utf8'));

buf.fill("hello");
console.log(buf);
console.log(buf.toString('utf8'));
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值