首页 > 解决方案 > 如何在两个字节中转换超过 256 的十六进制值

问题描述

我正在尝试将大于 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?

标签: javaarraystype-conversionhexbyte

解决方案


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)。


推荐阅读