Java byte[]和short[]之间的相互转换

来源:互联网 发布:java中高级笔试面试题 编辑:程序博客网 时间:2024/05/21 10:17

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 intint in = ByteBuffer.wrap(ba).order(ByteOrder.LITTLE_ENDIAN).getInt();byte [] ab = null;// int to 4 bytes method 1ab = ByteBuffer.allocate(4).order(ByteOrder.LITTLE_ENDIAN).putInt(in).array();// int to 4 bytes method 2ab = new byte[4];ByteBuffer.wrap(ab).order(ByteOrder.LITTLE_ENDIAN).asIntBuffer().put(in);


 


原创粉丝点击