java - 在JAVA中将短数组转换为字节数组

标签 java byte bytearray short

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

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 };

通过使用此链接 Converting short array to byte array两种转换方式,我得到以下两个不同的byte数组:

 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};

`

你能帮我看看哪个是正确的吗?

最佳答案

您对 asShortBuffer 的使用有点接近。应该是:

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

关于java - 在JAVA中将短数组转换为字节数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19584885/

相关文章:

silverlight-4.0 - 银光 4.0 : How to convert byte[] to image?

c - 抽象出这个过程是否值得?

java - 翻转存储为 byte[] 数组的图像

java - Java 实现监控线程

java - wsimport 为列表创建包装类

java - 将字符写入表中

python - 从字节中删除 '\x'

java - 使用 javax.mail 在 Java 中发送电子邮件时出现异常

java - 通过抽象来强制执行 hashCode 和 equals 是否有任何优势?

python - 在python中将字节转换为位