使用该方式可以压缩ipv4和ipv6存储大小和传输数据时的数据大小,尤其是socket场景,现在流量的成本相对于性能还是比较高的。
ipv4转换成int和反向转换java实现
public static void main(String[] args) throws IOException {
byte[] ip = new byte[4];
ip[0] = ip[1] = ip[2] = ip[3] = (byte)255;
System.out.println(Arrays.toString(ip));
//压缩成Integer
int ipCompress= byte4ToInt(ip, 0);
System.out.println(ipCompress);
//解压成字节数组
byte[] ipDecompress = intToByte4(ipCompress);
System.out.println(Arrays.toString(ipDecompress));
}
public static int byte4ToInt(byte[] bytes, int off) {
int b0 = bytes[off] & 0xFF;
int b1 = bytes[off + 1] & 0xFF;
int b2 = bytes[off + 2] & 0xFF;
int b3 = bytes[off + 3] & 0xFF;
return (b0 << 24) | (b1 << 16) | (b2 << 8) | b3;
}
public static byte[