import java.nio.ByteOrder; /** */ public class AnyIdUtil { public final static boolean IS_BIG_ENEIAN = (ByteOrder.nativeOrder() == ByteOrder.BIG_ENDIAN); public static byte[] int2bytes(int value) { byte[] bytes = new byte[4]; if (!IS_BIG_ENEIAN) { // 小端 bytes[3] = (byte) ((value >> 24) & 0xFF); bytes[2] = (byte) ((value >> 16) & 0xFF); bytes[1] = (byte) ((value >> 8) & 0xFF); bytes[0] = (byte) (value & 0xFF);//byte[0] 存儲 數據高位 } else {//大端 bytes[0] = (byte) ((value >> 24) & 0xFF); //byte[0] 存儲數據高位 bytes[1] = (byte) ((value >> 16) & 0xFF); bytes[2] = (byte) ((value >> 8) & 0xFF); bytes[3] = (byte) (value & 0xFF); } return bytes; } public static int bytes2int(byte[] bytes) { int value = 0; if (!IS_BIG_ENEIAN) { value = (int) ((bytes[0] & 0xFF) | ((bytes[1] & 0xFF) << 8) | ((bytes[2] & 0xFF) << 16) | ((bytes[3] & 0xFF) << 24)); } else { value = (int) (((bytes[0] & 0xFF) << 24) | ((bytes[1] & 0xFF) << 16) | ((bytes[2] & 0xFF) << 8) | (bytes[3] & 0xFF)); } return value; } }
這個更好理解:java