【问题标题】:Long to Byte Array Invalid长到字节数组无效
【发布时间】:2018-08-09 13:18:14
【问题描述】:

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

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: 0x60from hex = 96,就像它应该的那样 (afaik)。

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

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};

【问题讨论】:

  • 你怎么称呼longToBytes(long x),你得到的结果是逻辑我不明白你到底是什么!!
  • @YCF_L 更新了帖子,因为我猜它还不够清楚。

标签: java hex byte


【解决方案1】:

一个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 以获得合理的结果。

【讨论】:

  • 我刚刚添加到我的帖子中,因为我猜它不够清楚。我想要的是获取我提供的初始字节数组,而不是我得到的,这与你得到的相反。
  • @Swedz 很抱歉造成误解;添加了单个位掩码的拆分。参见 als Integer.lowestOneBit 迭代单个位。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-11-24
  • 1970-01-01
  • 1970-01-01
  • 2011-02-24
相关资源
最近更新 更多