将long转换为byte数组并将其添加到另一个数组
我想更改字节数组中的值以将长时间戳值放入MSB中。有人能告诉我什么是最好的方法。我不想逐位插入值,我认为这是非常低效的。
I want to change a values in byte array to put a long timestamp value in in the MSBs. Can someone tell me whats the best way to do it. I do not want to insert values bit-by-bit which I believe is very inefficient.
long time = System.currentTimeMillis();
Long timeStamp = new Long(time);
byte[] bArray = new byte[128];
我想要的是:
byte[0-63] = timeStamp.byteValue();
这样的事情是可能的。在此字节数组中编辑/插入值的最佳方法是什么。因为字节是原始的我不认为有一些我可以使用的直接实现?
Is something like this possible . What is the best way to edit/insert values in this byte array. since byte is a primitive I dont think there are some direct implementations I can make use of?
编辑:
似乎 System.currentTimeMillis()
比 Calendar.getTimeInMillis()
快,所以用它替换上面的代码。如果错误,请纠正我。
It seems that System.currentTimeMillis()
is faster than Calendar.getTimeInMillis()
, so replacing the above code by it.Please correct me if wrong.
有多种方法可以做到:
-
使用
ByteBuffer
(最佳选择 - 简洁易读):
Use a
ByteBuffer
(best option - concise and easy to read):
byte[] bytes = ByteBuffer.allocate(Long.SIZE / Byte.SIZE).putLong(someLong).array();
您还可以使用 DataOutputStream
(更详细):
You can also use DataOutputStream
(more verbose):
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(baos);
dos.writeLong(someLong);
dos.close();
byte[] longBytes = baos.toByteArray();
最后,您可以手动执行此操作(取自 LongSerializer
在Hector的代码中)(更难阅读):
Finally, you can do this manually (taken from the LongSerializer
in Hector's code) (harder to read):
byte[] b = new byte[8];
for (int i = 0; i < size; ++i) {
b[i] = (byte) (l >> (size - i - 1 << 3));
}
然后你可以追加这些字节通过一个简单的循环到你现有的数组:
Then you can append these bytes to your existing array by a simple loop:
// 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];
}