我想更改字节数组中的值以将长时间戳值放入 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();
这样的事情可能吗.在此字节数组中编辑/插入值的最佳方法是什么.因为 byte 是一个原语,我不认为有一些我可以使用的直接实现?
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();
最后,您可以手动执行此操作(取自 Hector 代码中的 LongSerializer)(更难阅读):
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];
}
这篇关于将 long 转换为字节数组并将其添加到另一个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!
“Char 不能被取消引用"错误quot;Char cannot be dereferencedquot; error(“Char 不能被取消引用错误)
Java Switch 语句 - 是“或"/“和"可能的?Java Switch Statement - Is quot;orquot;/quot;andquot; possible?(Java Switch 语句 - 是“或/“和可能的?)
Java替换字符串特定位置的字符?Java Replace Character At Specific Position Of String?(Java替换字符串特定位置的字符?)
具有 int 和 char 操作数的三元表达式的类型是什么What is the type of a ternary expression with int and char operands?(具有 int 和 char 操作数的三元表达式的类型是什么?)
读取文本文件并存储出现的每个字符Read a text file and store every single character occurrence(读取文本文件并存储出现的每个字符)
为什么我需要在 byte 和 short 上显式转换 char 原语Why do I need to explicitly cast char primitives on byte and short?(为什么我需要在 byte 和 short 上显式转换 char 原语?)