【问题标题】:How to convert hex value more than 256 in two bytes如何在两个字节中转换超过 256 的十六进制值
【发布时间】:2019-09-08 20:56:29
【问题描述】:

我正在尝试将大于 255(无符号)的十六进制值存储到两个字节中。下面是示例代码:

public class Test {
    public static void main(String[] args) {
        byte b = (byte)0x12c; // output : 44
        System.out.println(b);
    }
}

示例:当我将 300 转换为十六进制时,它将是 12c,它应该以字节为 (44, 1)。为什么java在第一个字节中保存44?

【问题讨论】:

  • 你希望它去哪里,为什么?
  • 0x12c0001_0010_1100。转换为byte 仅保留int 的最低有效8 位,在您的示例中为0010_1100,等于44
  • long 向下转换为int 时也是如此。如果您不熟悉它们,可能会遇到许多转换问题。在 Java 语言规范Kinds of Conversion 中阅读所有关于它们的信息。
  • 感谢@Jacob 的回复。但是在 400(而不是 300 0x12c)的情况下,它会打印 -112 但它应该将 144 和 1 打印为 0001_1001_0000。

标签: java arrays type-conversion hex byte


【解决方案1】:
byte[] bytes = new byte[2];
ByteBuffer bbuf = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN):
bbuf.putShort((short) 0x12c);

byte[] bytes = new byte[4];
ByteBuffer bbuf = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN):
bbuf.putInt(0x12c);

System.out.println(Arrays.toString(bytes));

或者你自己计算。

在这里,我们创建了我们想要的两个字节,在它周围包裹了一个 ByteBuffer,这样我们就可以读取和写入几个数字原始类型。您需要小端字节序(2c 优先)。

【讨论】:

    【解决方案2】:

    您需要将值存储到更大的数据类型(long 或 int)中,然后只取前 16 个无关紧要的位

    int raw = (int)0x12c;
    int masked = raw & 0x00ff
    System.out.println(masked);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-23
      • 2012-08-08
      • 2019-07-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多