用例
通过一个无符号短整型代表两个无符号字节(Major Version、Minor Version)
代码实现
/** * get an unsigned short (2 bytes) based on the high (1 byte) and low (1 byte) * * @param high * @param low * @return unsigned short * @throws NumberFormatException */
public static int getVersion(short high, short low) throws NumberFormatException {
short MAX_VALUE = 0xFF;
int MIN_VALUE = 0x01;
if (high < MIN_VALUE || high > MAX_VALUE || low < MIN_VALUE || low > MAX_VALUE) {
throw new NumberFormatException("high value " + high + " or low value " + low + "greater than " + MAX_VALUE +
" or high value " + high + " or low value " + low + "less than " + MIN_VALUE);
}
return (high << 8) + low;//unsigned short
}
/** * get high (1 byte) and low (1 byte) values based on an unsigned short (2 bytes) * * @param i unsigned short * @return {high,low} * @throws NumberFormatException */
public static short[] getVersion(int i) throws NumberFormatException {
int MAX_VALUE = 0xFFFF;
int MIN_VALUE = 0x01;
if (i < MIN_VALUE || i > MAX_VALUE) {
throw new NumberFormatException("value " + i + " greater than " + MAX_VALUE + " or less than " + MIN_VALUE);
}
short high = (short) (i >> 8);//unsigned byte
short low = (short) (i & 0x00ff);//unsigned byte
return new short[]{high, low};
}