package com.zy.acs.common.utils;
|
|
import java.nio.charset.Charset;
|
import java.nio.charset.StandardCharsets;
|
|
public class ByteUtils {
|
|
public static short getShort(byte[] data, int index) {
|
return (short) (((data[index] & 0xFF) << 8) | (data[index + 1] & 0xFF));
|
}
|
|
public static int getInt(byte[] data, int index) {
|
return ((data[index] & 0xFF) << 24) |
|
((data[index + 1] & 0xFF) << 16) |
|
((data[index + 2] & 0xFF) << 8) |
|
(data[index + 3] & 0xFF);
|
}
|
|
public static long getLong(byte[] data, int index) {
|
return ((long) (data[index] & 0xFF) << 56) |
|
((long) (data[index + 1] & 0xFF) << 48) |
|
((long) (data[index + 2] & 0xFF) << 40) |
|
((long) (data[index + 3] & 0xFF) << 32) |
|
((long) (data[index + 4] & 0xFF) << 24) |
|
((long) (data[index + 5] & 0xFF) << 16) |
|
((long) (data[index + 6] & 0xFF) << 8) |
|
(data[index + 7] & 0xFF);
|
}
|
public static double getDouble(byte[] data, int index) {
|
long bits = ((long) (data[index] & 0xFF) << 56) |
|
((long) (data[index + 1] & 0xFF) << 48) |
|
((long) (data[index + 2] & 0xFF) << 40) |
|
((long) (data[index + 3] & 0xFF) << 32) |
|
((long) (data[index + 4] & 0xFF) << 24) |
|
((long) (data[index + 5] & 0xFF) << 16) |
|
((long) (data[index + 6] & 0xFF) << 8) |
|
(data[index + 7] & 0xFF);
|
return Double.longBitsToDouble(bits);
|
}
|
/**
|
* 将字节数组中的每个字节转换为一个布尔值(非零为 true)。
|
* @param data 源字节数组
|
* @param start 起始索引(包含)
|
* @param count 要转换的字节个数(决定了返回数组的长度)
|
* @return 布尔数组,长度 = count
|
*/
|
public static boolean[] getBooleans(byte[] data, int start, int count) {
|
boolean[] result = new boolean[count];
|
for (int i = 0; i < count; i++) {
|
result[i] = data[start + i] != 0;
|
}
|
return result;
|
}
|
|
/**
|
* 将字节数组的一部分转换为字符串(使用指定字符集)
|
* @param data 源字节数组
|
* @param start 起始索引
|
* @param length 字节长度
|
* @param charset 字符集(如 StandardCharsets.US_ASCII)
|
* @return 转换后的字符串,自动去除末尾的空字符('\0')和空格
|
*/
|
public static String getString(byte[] data, int start, int length, Charset charset) {
|
if (data == null || start < 0 || length <= 0 || start + length > data.length) {
|
return "";
|
}
|
byte[] sub = new byte[length];
|
System.arraycopy(data, start, sub, 0, length);
|
String raw = new String(sub, charset);
|
// 去除末尾的空字符和空格(常见于固定长度字符串)
|
return raw.replaceAll("[\0\\s]+$", "");
|
}
|
|
/**
|
* 将字节数组的一部分转换为字符串(默认使用 UTF-8)
|
*/
|
public static String getString(byte[] data, int start, int length) {
|
return getString(data, start, length, StandardCharsets.UTF_8);
|
}
|
|
/**
|
* 将字节数组的一部分转换为 ASCII 字符串(Modbus 最常用)
|
*/
|
public static String getAsciiString(byte[] data, int start, int length) {
|
return getString(data, start, length, StandardCharsets.US_ASCII);
|
}
|
|
|
}
|