在JAVA中将短数组转换为字节数组 [英] Converting short array to byte array in JAVA

查看:170
本文介绍了在JAVA中将短数组转换为字节数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对如何将数组转换为 byte 数组感到困惑。
例如我有以下数组

I am confused on how to convert short array to byte array. E.g. I have the follwoing short array

short[] shrt_array = new short[]{ 0x4 , 0xd7 , 0x86, 0x8c, 0xb2, 0x14, 0xc, 0x8b, 0x2d, 0x39, 0x2d, 0x2d, 0x27, 0xcb, 0x2e, 0x79, 0x46, 0x36, 0x9d , 0x62, 0x2c };

使用此链接将短数组转换为字节数组这两种转换方法,我得到以下两个不同的字节数组:

By using this link Converting short array to byte array the two methods of conversion, I get the following two different byte arrays:

 expectedByteArray = new byte[] {
    (byte) 0x4, (byte) 0xd7, (byte) 0x86, 
    (byte) 0x8c, (byte) 0xb2, (byte) 0x14,  
    (byte) 0xc, (byte) 0x8b, (byte) 0x2d,
    (byte) 0x39, (byte) 0x2d, (byte) 0x2d, 
    (byte) 0x27, (byte) 0xcb, (byte) 0x2e, 
    (byte) 0x79, (byte) 0x46, (byte) 0x36,
    (byte) 0x9d, (byte) 0x62, (byte) 0x2c,  
    (byte) 0x0,  (byte) 0x0,  (byte) 0x0, 
    (byte) 0x0,  (byte) 0x0,  (byte) 0x0,  
    (byte) 0x0,  (byte) 0x0,  (byte) 0x0,  
    (byte) 0x0,  (byte) 0x0,  (byte) 0x0,  
    (byte) 0x0,  (byte) 0x0,  (byte) 0x0,  
    (byte) 0x0,  (byte) 0x0,  (byte) 0x0,  
    (byte) 0x0,  (byte) 0x0,  (byte)0x0};

第二个结果:`

expectedByteArray = new byte[] {
(byte) 0x4,  (byte) 0x0, (byte) 0xd7,  
(byte) 0x0,  (byte) 0x86,  (byte) 0x0,
(byte) 0x8c,  (byte) 0x0, (byte) 0xb2, 
(byte) 0x0,  (byte) 0x14,  (byte) 0x0, 
(byte) 0xc,  (byte) 0x0, (byte) 0x8b, 
 (byte) 0x0, (byte) 0x2d,  (byte) 0x0,
 (byte) 0x39,  (byte) 0x0, (byte) 0x2d, 
 (byte) 0x0, (byte) 0x2d,  (byte) 0x0, 
(byte) 0x27,  (byte) 0x0, (byte) 0xcb, 
 (byte) 0x0, (byte) 0x2e,  (byte) 0x0, 
(byte) 0x79,  (byte) 0x0, (byte) 0x46, 
 (byte) 0x0, (byte) 0x36,  (byte) 0x0,
(byte) 0x9d,  (byte) 0x0, (byte) 0x62,  
(byte) 0x0, (byte) 0x2c,  (byte) 0x0};

`

你能帮助我吗?是正确的。

Can you help me which is the right one.

推荐答案

你使用 asShortBuffer 有点接近。它应该是:

Your use of asShortBuffer was somewhat close. It should be:

ByteBuffer buffer = ByteBuffer.allocate(shrt_array.length * 2);
buffer.order(ByteOrder.LITTLE_ENDIAN);
buffer.asShortBuffer().put(shrt_array);
byte[] bytes = buffer.array();

这篇关于在JAVA中将短数组转换为字节数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆