Java byte[]和short[]之间的相互转换
做记录,方便使用。
以如下为例:
(1) 有如下byte数组,需将其转换为short数组。
byte [] ba = new byte[128];
转换方法:
short [] sa = new short[64];
ByteBuffer.wrap(ba).order(ByteOrder.LITTLE_ENDIAN).asShortBuffer().get(sa);
(2) 将上面的short数组再转换回byte数组。
ByteBuffer.wrap(ba).order(ByteOrder.LITTLE_ENDIAN).asShortBuffer().put(sa);
这里使用了小端字节序。比如byte值为1, 2的两位。按照小端字节序转换后的short值应该为:
0000001000000001,即513。
附带int和byte[]之间的转换:
byte [] ba = {1, 2, 3, 4};
// 4 bytes to int
int in = ByteBuffer.wrap(ba).order(ByteOrder.LITTLE_ENDIAN).getInt();
byte [] ab = null;
// int to 4 bytes method 1
ab = ByteBuffer.allocate(4).order(ByteOrder.LITTLE_ENDIAN).putInt(in).array();
// int to 4 bytes method 2
ab = new byte[4];
ByteBuffer.wrap(ab).order(ByteOrder.LITTLE_ENDIAN).asIntBuffer().put(in);
本文详细介绍了Java中Byte[]与short[]之间的相互转换,包括使用ByteBuffer进行数据包装和字节序调整,以及如何进行int与byte[]的转换。重点讲解了小端字节序在转换过程中的应用。

被折叠的 条评论
为什么被折叠?



