使用方法 2,不要担心字节数组中的负值。字节在java中签名,所以如果你想将你的字节处理为0到255而不是-128到127,并且每个字节都针对0xFF。这会将字节提升为整数,并将是 0 - 255 之间的值。
更新
看到有关您将如何通过串行端口发送此信息的评论,您的字节数组没有任何问题。接收器(如果它是另一个 Java 程序)将必须通过与 0xFF 进行与运算来处理字节。另一个串行程序(例如在 C# 中)将接收字节(0x00 - 0xFF)
public static void main(String[] args) throws Exception {
byte[] bytearray = {0x02, 0x08, 0x16, 0x00, 0x00, 0x33, (byte)0xC6, 0x1B};
for (byte b : bytearray) {
System.out.printf("%d ", b);
}
System.out.println();
for (byte b : bytearray) {
System.out.printf("%d ", b & 0xFF);
}
}
输出:
2 8 22 0 0 51 -58 27
2 8 22 0 0 51 198 27
老的
public static void main(String[] args) throws Exception {
System.out.println(Byte.MIN_VALUE);
System.out.println(Byte.MAX_VALUE);
System.out.println(Byte.MIN_VALUE & 0xFF);
System.out.println((byte)-1 & 0xFF);
System.out.println((byte)-10 & 0xFF);
System.out.println((byte)-58 & 0xFF);
}
输出:
-128
127
128
255
246
198