0

我正在尝试将较大的十六进制字符串值转换为字节。关于转换有符号字节的信息是最大值为 0x7F 仅等于 127。但是现在我的我想将十六进制值 C6 转换为我应该收到 198 的字节。有没有办法做到这一点?

目前我已经使用以下方法测试了我的代码:

  1. static byte[] bytearray = {0x02, 0x08, 0x16, 0x00, 0x00, 0x33, (byte)(Integer.parseInt("C6",16) & 0xff), 0x1B};
  2. static byte[] bytearray = {0x02, 0x08, 0x16, 0x00, 0x00, 0x33, (byte)0xC6, 0x1B};

所有这些方法只给我相同的值 -58。

如果有人可以帮助我,我将不胜感激。谢谢

4

2 回答 2

2

使用方法 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
于 2015-06-23T01:54:59.487 回答
0

这是正确的,因为字节是用 java 签名的。如果你需要它在 0-255 之间而不是 -128 到 127 之间,你需要使用 short 或 int (或 long,我想。)

话虽如此,您仍然可以以该格式发送它,但是当您使用它时,您需要将其用作 int。否则你将永远得到负数。

于 2015-06-23T01:44:56.033 回答