//取中间6位
static int get_bit_6(unsigned char c)
{
unsigned char b_mask = c & 127 ; //去掉最高位
b_mask = b_mask >>1; //去掉最低位
return b_mask;
}
//2个字节组合一个int
static int getLen(unsigned char c1, unsigned char c2)
{
c1 = c1 & 127; //去掉最高位
c1 = c1 << 6; //最低2位作为组合的最高2位
return c1|c2;
}
//读取不定长int
static int readInt2(unsigned char data[], int length)
{
// byte[] data = hexToByteArray("14 00 00 68 0c 32 2e 31 30 2e 39");
// byte[] data = hexToByteArray("ce 03 00 68 0c 32 2e 31 30 2e 39");
// byte[] data = hexToByteArray("8a 0f 00 68 0c 32 2e 31 30 2e 39");
// byte[] data = hexToByteArray("ea 8a ce ce ce ce 03 00 68 0c 32 2e 31 30 2e 39");
int curr = 0;
int nValue = 0;
if ((data[curr] & 128) == 128 ) // 10000000 判断最高位是否是1
{
nValue = (data[curr] & 127 ) >> 1 ; // 01111111 第一个字节只取6bit
int lMove = 6 ;
int next = curr + 1;
while (next < length) {
if ((data[next] & 128) == 128 ) {
nValue = ( (data[next] & 127) << lMove ) | nValue ; //后面只去头
lMove += 7 ;
}else {
nValue = ( (data[next] & 127) << lMove ) | nValue ;
break;
}
next = next + 1;
}
curr = curr + 1;
}
else
{
nValue = (data[curr] & 127 ) >> 1;
}
return nValue;
}
//转为不定长Int
static dInt turnInt(int nValue){
dInt dValue;
if(1048575 < nValue) //四个字节
{
nValue = nValue - 1048575;
dValue.c1 = (unsigned char)((63 << 1) | 128); //左移一位,增加最低位, 设置最高位1
dValue.c2 = (unsigned char)(255); //8个位都是1,最高位是标记位
dValue.c3 = (unsigned char)(255); //8个位都是1,最高位是标记位
dValue.c4 = (unsigned char)nValue;
}
else if(8191 < nValue && nValue < 1048575) //111111 1111111 1111111 3个字节
{
nValue = nValue - 8191;
dValue.c1 = (unsigned char)((63 << 1) | 128); //左移一位,增加最低位, 设置最高位1
dValue.c2 = (unsigned char)(255); //8个位都是1,最高位是标记位
dValue.c3 = (unsigned char)nValue;
}
if(63 < nValue) // 01111110 01111111 2个字节
{
nValue = nValue - 63;
dValue.c1 = (unsigned char)((63 << 1) | 128); //左移一位,增加最低位, 设置最高位1
dValue.c2 = (unsigned char)nValue;
}
else{ //00111111 一个字节
dValue.c1 = (unsigned char)(nValue << 1); //左移一位,增加最低位
}
return dValue;
}
//写入不定长
void WriteTurnInt(int nValue)
{
dInt dValue = turnInt(nValue);
Write(dValue.c1);
if(0 < dValue.c2)
Write(dValue.c2);
if(0 < dValue.c3)
Write(dValue.c3);
if(0 < dValue.c4)
Write(dValue.c4);
}
void WriteTurnShort(unsigned short nValue)
{
if(nValue <= 255)
{
unsigned char c1 = 0;
Write((unsigned char&)c1);
Write((unsigned char&)nValue);
}
else
{
unsigned char c1 = nValue - 255;
Write((unsigned char&)c1);
c1 = 255;
Write((unsigned char&)c1);
}
}
Protobuf数据格式解析
https://zhuanlan.zhihu.com/p/598480843
意思就是int足够小只用一个字节去存,和protobuf的有一点差别