問題描述
我想更改字節(jié)數(shù)組中的值以將長時間戳值放入 M??SB.有人可以告訴我最好的方法是什么.我不想逐位插入值,我認為這是非常低效的.
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();
這樣的事情可能嗎.在此字節(jié)數(shù)組中編輯/插入值的最佳方法是什么.因為 byte 是一個原語,我不認為有一些我可以使用的直接實現(xiàn)?
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
(更詳細):
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(baos);
dos.writeLong(someLong);
dos.close();
byte[] longBytes = baos.toByteArray();
最后,您可以手動執(zhí)行此操作(取自 Hector 代碼中的 LongSerializer
)(更難閱讀):
byte[] b = new byte[8];
for (int i = 0; i < size; ++i) {
b[i] = (byte) (l >> (size - i - 1 << 3));
}
然后您可以通過一個簡單的循環(huán)將這些字節(jié)附加到現(xiàn)有數(shù)組中:
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];
}
這篇關于將 long 轉(zhuǎn)換為字節(jié)數(shù)組并將其添加到另一個數(shù)組的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!