在 Java 中将 byte[] 转换为 short[]

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14033217/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 14:49:20  来源:igfitidea点击:

Converting a byte[] to short[] in Java

java

提问by Little Child

Possible Duplicate:
byte array to short array and back again in java

可能的重复:
字节数组到短数组,然后在 java 中再次返回

the encodeAudio()method in Xuggler has the following parameters:

encodeAudio()Xuggler 中的方法有以下参数:

  • int streamIndes
  • 整数流索引
  • short[] samples
  • 短[]样本
  • long timeStamp
  • 长时间戳
  • TimeUnit unit
  • 时间单位



  • 使用TargetDataLineTargetDataLinefrom javax.sound.sampledjavax.sound.sampledI 可以将数据读入byte[]byte[]数组

    byte[] tempBuffer = new byte[10000];
    fromMic.read(tempBuffer,0,tempBuffer.length);
    

    But the problem is that the samplesargument needs short[]

    但问题是samples论证需要short[]

    回答by fge

    You are lucky enough that byteis "fully castable" to short, so:

    您很幸运可以byte“完全铸造”到short,因此:

    // Grab size of the byte array, create an array of shorts of the same size
    int size = byteArray.length;
    short[] shortArray = new short[size];
    
    for (int index = 0; index < size; index++)
        shortArray[index] = (short) byteArray[index];
    

    And then use shortArray.

    然后使用shortArray.

    Note: as far as primitive type goes, Java always treats them in big endian order, so converting, say, byte ffwill yield short 00ff.

    注意:就原始类型而言,Java 总是以大端顺序处理它们,因此转换,例如, byteff将产生 short 00ff