[英]Long to Byte Array Invalid
I'm starting to use bytes and hexes to try to store some data easier. 我开始使用字节和十六进制来尝试更容易地存储一些数据。 This is currently what I'm doing:
这是我目前正在做的事情:
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);
This all works fine, hex: 0x60
and from hex = 96
, just as it is supposed to be (afaik). 一切正常,
hex: 0x60
, from hex = 96
,正如它应该是(afaik)一样。
However when I attempt to convert 96 back to the byte array, using longToBytes(cosmetics)
: 但是,当我尝试使用
longToBytes(cosmetics)
将96转换回字节数组时:
public static byte[] longToBytes(long x) {
ByteBuffer buffer = ByteBuffer.allocate(Long.BYTES);
buffer.putLong(x);
return buffer.array();
}
It doesn't return the array I initially used, it gives: 0, 0, 0, 0, 0, 0, 0, 96
它不返回我最初使用的数组,而是给出:
0, 0, 0, 0, 0, 0, 0, 96
But what I want it to give me, is the array that I initially used: 但是我想要它给我的是我最初使用的数组:
byte[] data = new byte[] {0x20, 0x40};
A long has 8 bytes, and you put the byte 0x20|0x40 = 0x60 = 96 as long into the array. long有8个字节,然后将字节0x20 | 0x40 = 0x60 = 96放入数组中。
Java per default orders the bytes bigendian , so the least significant byte, 96, comes last. Java默认情况下将字节bigendian排序 ,因此最低有效字节96排在最后。
To do it the other way around: 反过来也可以:
public static byte[] longToBytes(long x) {
return ByteBuffer.allocate(Long.BYTES)
.order(ByteOrder.LITTLE_ENDIAN)
.putLong(x)
.array();
}
Should give 应该给
96, 0, 0, 0, 0, 0, 0, 0
After refined question 经过提炼的问题
One cannot determine that 96 stemmed from 0x20|0x40, but I'll assume you want the individual bit masks. 不能确定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();
}
The parameter could/should be a byte or 0-256 restricted int for a sensible result. 该参数可以/应该是一个字节或0-256受限制的int值,以获取合理的结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.