概述
ByteBuf
创建缓冲区ByteBuf
1、字节数组byte[] bytes,长度为28012.
{16, 113, 109, 0, 0, 1, -128, 0, -86, -67, +28012 more}
2、写入缓冲区内容
//创建缓冲区:
//ridx:0,
widx:0,
cap:256
ByteBuf binaryBuf = Unpooled.buffer();
if (bytes != null) {
//数组长度为28022
int strLength = bytes.length;
//写入缓冲区内容
//ridx:0,
widx:28022,
cap:32768
binaryBuf.writeBytes(bytes);
}
截取ByteBuf
1、截取ByteBuf 中,从偏移地址num开始,长度为needBytes的ByteBuf
//偏移地址:
int num = 5770;
//字节长度
int needBytes = 3;
//截取出新的ByteBuf
ridx:0,
widx:3,
cap:3/3
ByteBuf dstBuf=binaryBuf.slice(num, needBytes);
//dstBuf.readableBytes()是返回可被读取的字节数:3
//创建数组大小为3的dstBytes :{0,0,0}
byte[] dstBytes = new byte[dstBuf.readableBytes()];
//dstBuf.readerIndex()的结果为0
//getBytes将该缓冲区中从给定索引readerIndex开始的数据传送到指定的目的地dstBytes
dstBuf.getBytes(dstBuf.readerIndex(), dstBytes);
byteStr+=util.byteArrToBinStr(dstBytes);
字节数组转string,二进制补全8位
//b:{0,0,0}
public String byteArrToBinStr(byte[] b) {
StringBuffer result = new StringBuffer();
for(int i = 0; i < b.length; ++i) {
//1个字节8bit,3个字节24个位
//"000000000000000000000000"
result.append(StringUtils.leftPad(Integer.toBinaryString(b[i] & 255), 8, '0'));
}
return result.toString();
}
最后
以上就是眼睛大灰狼为你收集整理的Netty的ByteBuf中截取某段字节,再字节数组转二进制string的全部内容,希望文章能够帮你解决Netty的ByteBuf中截取某段字节,再字节数组转二进制string所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复