如何在两个字节中转换大于256的十六进制值

时间:2019-04-18 13:46:27

标签: java arrays type-conversion hex byte

我试图将大于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?

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

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

int raw = (int)0x12c;
int masked = raw & 0x00ff
System.out.println(masked);
相关问题