add methods

This commit is contained in:
Looly
2022-05-16 10:03:16 +08:00
parent 541ab9ed55
commit 5d4e18a63b
2 changed files with 18 additions and 4 deletions

View File

@@ -74,12 +74,25 @@ public class ByteUtil {
* @param byteOrder 端序
* @return short值
*/
public static short bytesToShort(byte[] bytes, ByteOrder byteOrder) {
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);
}
}