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).
However when I attempt to convert 96 back to the byte array, using longToBytes(cosmetics)
:
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
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.
Java per default orders the bytes bigendian , so the least significant byte, 96, comes last.
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.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.