[编织消息框架][设计协议]优化long,int转换

时间:2023-03-09 00:04:43
[编织消息框架][设计协议]优化long,int转换

理论部分

一个long占8byte,大多数应用数值不超过int每次传输多4byte会很浪费

有没有什么办法可以压缩long或int呢?

答案是有的,原理好简单,如果数值不超过int.max_value的话就"自动变成"int类型

现在问题又出现了读取时如果知道原来的类型是什么?

可以先写一个byte是什么类型,再写入值,读时先读一个byte,根据类型做不同解释

源码解读

 public abstract class PacketUtil {

     public final static byte BIT_8 = Byte.MAX_VALUE;
public final static short BIT_16 = Short.MAX_VALUE;
public final static int BIT_32 = Integer.MAX_VALUE;
public final static long BIT_64 = Long.MAX_VALUE;
/***
读取自适应数字
*/
public static Number autoReadNum(int offset, byte[] bytes) {
byte bit = bytes[offset];
offset++;
Number ret = null;
switch (bit) {
case 9: //readLong
ret = readLong(offset, bytes);
break;
case 5: //readInt
ret = readInt(offset, bytes);
break;
case 3: //readShort
ret = readShort(offset, bytes);
break;
case 2: //readByte
ret = readByte(offset, bytes);
break;
case 1: //zero
ret = (byte) 0;
break;
default:
throw new QSocketException(QCode.SOCKET_UNKNOWN_OPCODE, "auto bytes unknown opcode :" + bit);
} return ret;
}
/***
写入自适应数字
*/
public static byte autoWriteNum(int offset, Number v, byte[] ret) {
byte bit = getAutoWriteLen(v);
writeByte(offset, bit, ret);
offset++;
switch (bit) {
case 9: //writeLong
writeLong(offset, v.longValue(), ret);
break;
case 5: //writeInt
writeInt(offset, v.intValue(), ret);
break;
case 3: //writeShort
writeShort(offset, v.shortValue(), ret);
break;
case 2: //writeByte
writeByte(offset, v.byteValue(), ret);
break;
case 1: //zero
break;
default:
throw new QSocketException(QCode.SOCKET_UNKNOWN_OPCODE, "auto bytes unknown opcode :" + bit);
}
return bit;
}
/***
获取自适合数字大小
*/
public static byte getAutoWriteLen(Number value) {
long v = value.longValue();
if (v < 0) {
v = -v;
}
byte bit = 0;
//如果为零返回类型为0
if (v == 0) {
bit = 1;
} else if (v > BIT_32) { //如果超过int max 认为是long类型
bit = 9;
} else if (v > BIT_16) {//如果超过short max 认为是int类型
bit = 5;
} else if (v > BIT_8) { //如果超过byte max 认为是short类型
bit = 3;
} else { //否则为byte类型
bit = 2;
}
return bit;
}
}

如果数值为0时,可以减小到1byte,少于short.max_value 占3byte,减少60%空间