如何将短整数数组转换为字节数组。

19

我在这里找到了将short类型转换为byte数组的方法,以及byte数组转换为short数组的方法,但是没有找到将short数组转换为byte数组的方法。

以下是代码实现转换的部分:

while(!stopped)
        { 
            Log.i("Map", "Writing new data to buffer");
            short[] buffer = buffers[ix++ % buffers.length];

            N = recorder.read(buffer,0,buffer.length);
            track.write(buffer, 0, buffer.length);

            byte[] bytes2 = new byte[N];

我已经尝试过

              int i = 0;
              ByteBuffer byteBuf = ByteBuffer.allocate(N);
              while (buffer.length >= i) {
                  byteBuf.putShort(buffer[i]);
                  i++;
        }

bytes2 = byteBuf.array();

    ByteBuffer.wrap(bytes2).order(ByteOrder.LITTLE_ENDIAN).asShortBuffer().put(buffer);

然而,我在两个地方都收到了这个错误(尽管错误信息不完全相同,但非常相似):

05-29 13:41:12.021: W/AudioTrack(9758): obtainBuffer() track 0x30efa0 disabled, restarting

05-29 13:41:12.857: W/AudioWorker(9758): Error reading voice AudioWorker

05-29 13:41:12.857: W/AudioWorker(9758): java.nio.BufferOverflowException

05-29 13:41:12.857: W/AudioWorker(9758): at java.nio.ShortBuffer.put(ShortBuffer.java:422)

05-29 13:41:12.857: W/AudioWorker(9758): at java.nio.ShortToByteBufferAdapter.put(ShortToByteBufferAdapter.java:210)

05-29 13:41:12.857: W/AudioWorker(9758): at java.nio.ShortBuffer.put(ShortBuffer.java:391)

05-29 13:41:12.857: W/AudioWorker(9758): at com.avispl.nicu.audio.AudioWorker.run(AudioWorker.java:126)

为了提供尽可能多的信息,以下是使用字节数组之后的代码。

Log.i("Map", "test");
                //convert to ulaw
                read(bytes2, 0, N);

                //send to server
                os.write(bytes2,0,bytes2.length);

                System.out.println("bytesRead "+buffer.length);
                System.out.println("data "+Arrays.toString(buffer));
            }

不确定我应该从中得到什么。你发布的链接是西班牙语的,我不知道它是关于什么的,也许是关于相关性的一个笑话?我只想展示N是什么并避免问题。 - owen gerig
哦,亲爱的。我想@Bohemian是指http://www.sscce.org/,而不是http://www.ssccee.org/。 - Louis Wasserman
可能是Java中字节数组和短整型数组的相互转换的重复问题。 - patryk.beza
3个回答

44

我发现ByteBuffer在我分析的三种转换方法中是最慢的。请看下面...

平台:Nexus S,Android 4.1.1,无SIM卡

方法#1:使用ByteBuffer

byte [] ShortToByte_ByteBuffer_Method(short [] input)
{
  int index;
  int iterations = input.length;

  ByteBuffer bb = ByteBuffer.allocate(input.length * 2);

  for(index = 0; index != iterations; ++index)
  {
    bb.putShort(input[index]);    
  }

  return bb.array();       
}

方法二:直接操作二进制位

byte [] ShortToByte_Twiddle_Method(short [] input)
{
  int short_index, byte_index;
  int iterations = input.length;

  byte [] buffer = new byte[input.length * 2];

  short_index = byte_index = 0;

  for(/*NOP*/; short_index != iterations; /*NOP*/)
  {
    buffer[byte_index]     = (byte) (input[short_index] & 0x00FF); 
    buffer[byte_index + 1] = (byte) ((input[short_index] & 0xFF00) >> 8);

    ++short_index; byte_index += 2;
  }

  return buffer;
}

方法三:通过JNI使用C语言

TypeCast.java

package mynamespace.util;

public class TypeCast
{
  public static native byte [] shortToByte(short [] input);

  static
  {
    System.loadLibrary("type_conversion");
  }
}

native.c

#include <jni.h>
#include <string.h>

jbyteArray Java_mynamespace_util_TypeCast_shortToByte(JNIEnv *env, jobject obj, jshortArray input)
{
  jshort     *input_array_elements;
  int         input_length;

  jbyte      *output_array_elements;
  jbyteArray  output;

  input_array_elements = (*env)->GetShortArrayElements(env, input, 0);
  input_length         = (*env)->GetArrayLength(env, input);

  output                = (jbyteArray) ((*env)->NewByteArray(env, input_length * 2));
  output_array_elements = (*env)->GetByteArrayElements(env, output, 0);

  memcpy(output_array_elements, input_array_elements, input_length * 2);

  (*env)->ReleaseShortArrayElements(env, input, input_array_elements, JNI_ABORT);
  (*env)->ReleaseByteArrayElements(env, output, output_array_elements, 0);

  return output;
}

结果:

对于一个包含一百万个元素的输入数组,执行时间如下:

方法1 ByteBuffer: 865毫秒

方法2 Twiddle: 299毫秒

方法3 C: 39毫秒


请上传并提供 C 方法的 .SO 文件链接,这将非常有帮助。我不想仅为此下载 NDK。谢谢。 - kc ochibili

16

Java中short是16位类型,而byte是8位类型。如果您有一个循环,试图将N个short插入到长度为N字节的缓冲区中,那么它需要是2*N 字节长才能容纳所有数据。

ByteBuffer byteBuf = ByteBuffer.allocate(2*N);
while (N >= i) {
    byteBuf.putShort(buffer[i]);
    i++;
}

3
在Java中,使用foreach循环通常比使用for循环更快:for (short s : buffer) byteBuf.put(s); - EntangledLoops

0

以下是如何将短整型数组转换为字节数组。

注意:要改变字节序,请交换那些resultData[c++]行。当前为小端字节序。

  public byte[] getBytes(short[] data) {
       byte[] resultData = new byte[data.length * 2];
       int c = 0;
       for (int i = 0; i < data.length; i++) {
           resultData[c++] = (byte) (((data[i])) & 0xFF);
           resultData[c++] = (byte) (((data[i]) >>> 8) & 0xFF);
       }
       return resultData;
   }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接