有多种方法可以做到这一点:
使用
ByteBuffer
(最佳选择-简洁易读):byte[] bytes = ByteBuffer.allocate(Long.SIZE / Byte.SIZE).putLong(someLong).array();
您还可以使用
DataOutputStream
(更详细):
ByteArrayOutputStream baos = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(baos); dos.writeLong(someLong); dos.close(); byte[] longBytes = baos.toByteArray();
- 最后,您可以手动执行此操作(摘自
LongSerializer
Hector的代码)(较难阅读):
byte[] b = new byte[8]; for (int i = 0; i < size; ++i) { b[i] = (byte) (l >> (size - i - 1 << 3)); }然后,您可以通过一个简单的循环将这些字节追加到现有数组中:
// change this, if you want your long to start from // a different position in the array int start = 0; for (int i = 0; i < longBytes.length; i ++) { bytes[start + i] = longBytes[i]; }


