这是
Long number = 0x001122334455667788L;
我需要创建Long的最后6个字节的byte[]
。
所以它看起来像
byte[] bytes = {0x22,0x33,0x44,0x55,0x66,0x77,0x88};
制作这样的东西的正确方法是什么?
感谢任何回应
答案 0 :(得分:1)
java.lang.BigInteger
toByteArray()
答案 1 :(得分:1)
byte[] buffer = new byte[6];
buffer[0] = (byte)(v >>> 40);
buffer[1] = (byte)(v >>> 32);
buffer[2] = (byte)(v >>> 24);
buffer[3] = (byte)(v >>> 16);
buffer[4] = (byte)(v >>> 8);
buffer[5] = (byte)(v >>> 0);
这就是DataOutputStream.writeLong()
的作用(除了它写了所有的字节,或者当然)
答案 2 :(得分:1)
如何使用DataOutputStream?
ByteArrayOutputStream baos = new ByteArrayOutputStream(); // This will be handy.
DataOutputStream os = new DataOutputStream(baos);
try {
os.writeLong(number); // Write our number.
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
os.close(); // close it.
} catch (IOException e) {
e.printStackTrace();
}
}
return Arrays.copyOfRange(baos.toByteArray(), 2, 8); // Copy out the last 6 elements.
答案 3 :(得分:1)
您可以使用ByteBuffer
Long number = 0x001122334455667788L;
ByteBuffer buffer = ByteBuffer.allocate(8);
buffer.putLong(number);
byte[] full = buffer.array();
byte[] shorter = Arrays.copyOfRange(full, 2, 8); // get only the lower 6
答案 4 :(得分:1)
BigInteger
也会这样做。
BigInteger number = new BigInteger("001122334455667788", 16);
byte[] b = number.toByteArray();
// May need to tweak the `b.length - 6` if the number is less than 6 bytes long.
byte[] shortened = Arrays.copyOfRange(b, b.length - 6, b.length);
System.out.println(Arrays.toString(shortened));