Java 从long类型获取字节的最快方法

Java 从long类型获取字节的最快方法,java,arrays,get,byte,long-integer,Java,Arrays,Get,Byte,Long Integer,这是 Long number = 0x001122334455667788L; 我需要创建最后6个长字节的字节[] 所以它看起来就像 byte[] bytes = {0x22,0x33,0x44,0x55,0x66,0x77,0x88}; 做这种东西的正确方法是什么 感谢您的回复java.lang.BigIntegertoByteArray()java.lang.BigIntegertoByteArray() 这就是DataOutputStream.writeLong()所做的(除了它写入所

这是

Long number = 0x001122334455667788L;
我需要创建最后6个长字节的
字节[]

所以它看起来就像

byte[] bytes = {0x22,0x33,0x44,0x55,0x66,0x77,0x88};
做这种东西的正确方法是什么


感谢您的回复

java.lang.BigInteger
toByteArray()
java.lang.BigInteger
toByteArray()

这就是
DataOutputStream.writeLong()
所做的(除了它写入所有字节或进程)


这就是
DataOutputStream.writeLong()
所做的(除了写入所有字节或过程)

使用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.

使用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.

您可以使用
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

您可以使用
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

biginger
也可以

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

biginger
也可以

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

我只需要最后6个字节使用返回数组的最后6个元素。我只需要最后6个字节使用返回数组的最后6个元素。第一行必须是数字40?不是64岁?不是,40岁。你想扔掉长的前40位(5字节),保留第6个字节(从右边开始),第一行必须是数字40?不是64岁?不是,40岁。您希望丢弃长度的前40位(5个字节),保留第6个字节(从右侧开始)您的
数字超过64位,而
字节长度为7个字节,不是6-如果这是真的,则不能使用
Long
Long
。您的
数字超过64位,而
字节长度为7字节,而不是6-如果这是真的,则不能使用
Long
Long