add methods

This commit is contained in:
Looly 2022-05-16 09:58:25 +08:00
parent d52470e8e7
commit 4ab19a303c

View File

@ -77,11 +77,24 @@ public class ByteUtil {
* @return short值
*/
public static short bytesToShort(final byte[] bytes, final ByteOrder byteOrder) {
return bytesToShort(bytes, 0, byteOrder);
}
/**
* byte数组转short<br>
* 自定义端序
*
* @param bytes byte数组长度必须大于2
* @param start 开始位置
* @param byteOrder 端序
* @return short值
*/
public static short bytesToShort(final byte[] bytes, final int start, final ByteOrder byteOrder) {
if (ByteOrder.LITTLE_ENDIAN == byteOrder) {
//小端模式数据的高字节保存在内存的高地址中而数据的低字节保存在内存的低地址中
return (short) (bytes[0] & 0xff | (bytes[1] & 0xff) << Byte.SIZE);
return (short) (bytes[start] & 0xff | (bytes[start + 1] & 0xff) << Byte.SIZE);
} else {
return (short) (bytes[1] & 0xff | (bytes[0] & 0xff) << Byte.SIZE);
return (short) (bytes[start + 1] & 0xff | (bytes[start] & 0xff) << Byte.SIZE);
}
}