首页 > 解决方案 > 长到字节数组无效

问题描述

我开始使用字节和十六进制来尝试更轻松地存储一些数据。这就是我目前正在做的事情:

byte[] data = new byte[] {0x20, 0x40};
long cosmetics = 0;

for(byte d : data) {
    cosmetics = cosmetics | d;
    System.out.println(d + ": " + cosmetics);
}

String hex = Long.toHexString(cosmetics);
System.out.println("hex: 0x" + hex);
System.out.println("from hex: " + Long.decode("0x"+hex));

byte[] bytes = longToBytes(cosmetics);
String s = "";
for(byte b : bytes)
  s += b+", ";
System.out.println("bytes: " + s);

这一切都很好,hex: 0x60并且from hex = 96,就像它应该是(afaik)一样。

但是,当我尝试将 96 转换回字节数组时,使用longToBytes(cosmetics)

public static byte[] longToBytes(long x) {
    ByteBuffer buffer = ByteBuffer.allocate(Long.BYTES);
    buffer.putLong(x);
    return buffer.array();
}

它不返回我最初使用的数组,它给出:0, 0, 0, 0, 0, 0, 0, 96

但我希望它给我的是我最初使用的数组:

byte[] data = new byte[] {0x20, 0x40};

标签: javahexbyte

解决方案


long 有 8 个字节,您将字节 0x20|0x40 = 0x60 = 96 as long 放入数组中。

Java 默认对字节进行排序 bigendian,因此最低有效字节 96 排在最后。

反过来做:

public static byte[] longToBytes(long x) {
    return ByteBuffer.allocate(Long.BYTES)
            .order(ByteOrder.LITTLE_ENDIAN)
            .putLong(x)
            .array();
}

应该给

96, 0, 0, 0, 0, 0, 0, 0

提炼后的问题

无法确定 96 源自 0x20|0x40,但我假设您需要单独的位掩码。

byte[] longToBytes(long x) {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    int mask = 1;
    for (int i = 0; i < 8; ++i) {
        if ((mask & x) != 0) {
            baos.write(0xFF & (int)mask);
        }
        mask <<= 1;
    }
    return baos.toArray();
}

该参数可以/应该是一个字节或 0-256 受限 int 以获得合理的结果。


推荐阅读