问题:
目前自学Netty中,正好学到数据传输载体ByteBuf的使用,对于其中的get方法获取到的值不理解。
先输入byte类型的1、2、3、4,再输入int类型的12,最后输入byte类型的5、6。
输出buffer.getByte(3)=4,这个很容易理解,接下来我就懵逼了。
输出buffer.getShort(3)=1024,why?
输出buffer.getInt(3)=67108864,why?
解决:
总所周知:
byte: 1字节,8位,有符号
short:2字节,16位,有符号
int: 4字节,32位,有符号
long: 8字节,64位,有符号
所以:
index getshort(index) index
0----1: 0000 0001
1----2: 0000 0010 256+2(0和1) 0
2----3: 0000 0011 512+2+1(1和2) 1
3----4: 0000 0100 512+256+4(2和3) 2
4----12:0000 0000 1024(3和4) 3
5---- 0000 0000
6---- 0000 0000
7---- 0000 1100
8----5: 0000 0101
9----6: 0000 0110
short为2字节,16位,getshort(0)读取0和1两个字节的组合,故值为258;
getshort(1)读取1和2两个字节的组合,故值为515;(居然不是2和3,懵逼)
getshort(2)读取2和3两个字节的组合,故值为772;
getshort(3)读取3和4两个字节的组合,故值为1024;
getint()获取的值同理~