使用Integer存储版本号
格式为
1. (仿 java) 魔法数 1A2B占2个字节
2. 主版本号占1个字节(0~255)
3. 次版本号占1个字节(0~255)
可供升级的版本为 6W多个,基本够用了
/** * 1. 魔法数 1A2B占2个字节 * 2. 主版本号占1个字节(0~255) * 3. 次版本号占1个字节(0~255) */ static class Header implements Comparable<Header> { //魔法数 private final static short MagicValue = 0x1A2B; //魔法数 private short magicValue; //主版本号 private byte mainVersion; //次版本号 private byte subVersion; public Header(byte mainVersion, byte subVersion) { magicValue = MagicValue; this.mainVersion = mainVersion; this.subVersion = subVersion; } public int toInt() { //魔法值 右移16位,即占Int32的高16位 //主版本号 右移8位,即点Int32的低16位中的高8位 // 次版本号占低8位 return (magicValue & 0xFFFF) << 16 | (mainVersion & 0xFF) << 8 | (subVersion & 0xFF); } public static int toInt(Header header) { return header.toInt(); } public static Header toHeader(int headerInt) { // 首次校验header里的魔法位是不是正确的 int mv = (headerInt >> 16) & 0xFFFF; if (mv != MagicValue) { throw new RuntimeException("格式不对"); } byte mainVersion = (byte) ((headerInt >> 8) & 0xFF); byte subVersion = (byte) ((headerInt) & 0xFF); return new Header(mainVersion, subVersion); } public static int toInt(int mainVersion, int subVersion) { return (MagicValue & 0xFFFF) << 16 | (mainVersion & 0xFF) << 8 | (subVersion & 0xFF); } @Override public int compareTo(Header o) { if (o == null) { return 0; } return this.toInt() - o.toInt(); } @Override public String toString() { return "Header{" + //"magicValue=" + magicValue + "(" + String.format("%x", magicValue) + ")" + "magicValue=" + magicValue + "(" + Integer.toHexString(magicValue) + ")" + ", mainVersion=" + mainVersion + ", subVersion=" + subVersion + '}'; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Header header = (Header) o; return toInt() == header.toInt(); } @Override public int hashCode() { return toInt(); } } public static Header makeHeader(byte mainVersion, byte subVersion) { return new Header(mainVersion, subVersion); } public static void main(String[] args) { Header header = makeHeader((byte) 1, (byte) 1); System.out.println(header); int headerInt = header.toInt(); System.out.println(headerInt); Header header2 = Header.toHeader(headerInt); System.out.println(header2); Header header_1_20 = makeHeader((byte) 2, (byte) 20); System.out.println(header_1_20); System.out.println(header.compareTo(header_1_20)); System.out.println(Header.toHeader(539025921)); }
输出为:
Header{magicValue=6699(1a2b), mainVersion=1, subVersion=1} 439025921 Header{magicValue=6699(1a2b), mainVersion=1, subVersion=1} Header{magicValue=6699(1a2b), mainVersion=2, subVersion=20} -275
Exception in thread "main"
java.lang.RuntimeException: 格式不对
at com.g2.IntToByteArray$Header.toHeader(IpV4Utils.java:135) at com.g2.IntToByteArray.main(IpV4Utils.java:200) Process finished with exit code 1