簡體   English   中英

長到字節數組無效

[英]Long to Byte Array Invalid

我開始使用字節和十六進制來嘗試更容易地存儲一些數據。 這是我目前正在做的事情:

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

long有8個字節,然后將字節0x20 | 0x40 = 0x60 = 96放入數組中。

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值,以獲取合理的結果。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM