在Java中将字节数组转换为整数,反之亦然 [英] Convert a byte array to integer in Java and vice versa
问题描述
我想在Java中将一些数据存储到字节数组中。基本上只是每个数字最多可以占用2个字节的数字。
I want to store some data into byte arrays in Java. Basically just numbers which can take up to 2 Bytes per number.
我想知道如何将整数转换为2字节长字节数组,反之亦然。我发现了很多解决方案谷歌搜索,但大多数解释不到代码中发生的事情。有很多变化的东西,我不太懂,所以我很感激基本的解释。
I'd like to know how I can convert an integer into a 2 byte long byte array and vice versa. I found a lot of solutions googling but most of them don't explain what happens in the code. There's a lot of shifting stuff I don't really understand so I would appreciate a basic explanation.
推荐答案
使用找到的类 java.nio
命名空间,特别是 字节缓冲区
。它可以为你完成所有的工作。
Use the classes found in the java.nio
namespace, in particular, the ByteBuffer
. It can do all the work for you.
byte[] arr = { 0x00, 0x01 };
ByteBuffer wrapped = ByteBuffer.wrap(arr); // big-endian by default
short num = wrapped.getShort(); // 1
ByteBuffer dbuf = ByteBuffer.allocate(2);
dbuf.putShort(num);
byte[] bytes = dbuf.array(); // { 0, 1 }
这篇关于在Java中将字节数组转换为整数,反之亦然的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!