Convert long to byte array and add it to another array(将 long 转换为字节数组并将其添加到另一个数组)
问题描述
我想更改字节数组中的值以将长时间戳值放入 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 转换为字节数组并将其添加到另一个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:将 long 转换为字节数组并将其添加到另一个数组


基础教程推荐
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- RabbitMQ:消息保持“未确认"; 2022-01-01
- 存储 20 位数字的数据类型 2022-01-01
- Struts2 URL 无法访问 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- 修改 void 函数的输入参数,然后读取 2022-01-01
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01