有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Java将字节[]转换为双[],反之亦然

我正在做一些涉及读取音频数据的工作。我需要将音频数据字节[]转换为双[](反之亦然)。 我需要转换,使信号通过低通滤波器

要将表单字节转换为双字节,我使用以下代码段:

// where data is the byte array.
ByteBuffer byteBuffer = ByteBuffer.wrap(data);
// make sure that the data is in Little endian order.
byteBuffer.order(ByteOrder.LITTLE_ENDIAN);
// every double will represent 2 bytes (16bit audio sample)
// so the double[] is half length of byte[]
double[] doubleData = new double[data.length / 2];
int i = 0;
while (byteBuffer.remaining() > 2) {
    // read shorts (16bits) and cast them to doubles
    short t = byteBuffer.getShort();
    doubleData[i] = t;
    doubleData[i] /= 32768.0;
    i++;
}

我不知道这是否是最好的方法,尤其是它给出了“Java堆外空间异常”和大量数据字节

综上所述:

  1. 有没有更好的转换方法,即不消耗堆空间的方法
  2. 如何再次将双精度转换回字节

谢谢你的帮助

谢谢

萨默萨米


共 (4) 个答案

  1. # 1 楼答案

    只是堆空间的一个随机想法:您可以在以后处理数组时生成/= 32768.0

    编辑:代码输入错误

    short[] shortData = new short[data.length / 2];
    int i = 0;
    while (byteBuffer.remaining() > 2) {
        // read shorts (16bits) and cast them to doubles
        short t = byteBuffer.getShort();
        shortData[i] = t;
        i++;
    }
    
  2. # 2 楼答案

    看看HugeCollections

    The Huge collections library is designed to support large collections on data in memory efficiently without GC impact. It does this using heap less memory and generated code for efficiency.

    我知道这不是一个完整的答案(你要求任何帮助),但对于用java处理大量数据,你会在vanillajava博客上找到很多很棒的方法

  3. # 3 楼答案

    它真的需要是一个double[]我不是一个大风扇的浮动,但它会给你足够多的准确性和一半的大小

    如果要避免使用堆,请使用直接内存,即不要使用字节[]或双精度[],而是使用字节缓冲区、短缓冲区和浮动缓冲区作为直接内存

    顺便说一句:为字节设置字节顺序没有任何作用

    ByteBuffer bb = // use direct memory if possible.
    ShortBuffer sb = bb.order(ByteOrder.LITTLE_ENDIAN).asShortBuffer();
    FloatBuffer fb = ByteBuffer.allocateDirect(sb.remaining() * 4)
                     .order(ByteOrder.nativeOrder()).asFloatBuffer();
    while(sb.remaining()>0)
        fb.put(sb.get() / 32768.0f);
    
  4. # 4 楼答案

    你所使用的大量堆的东西只有“数据”,尤其是“双重数据”。因此,如果您正在寻找一种减少堆空间的方法,那么您找错了地方——您必须找到一种不同时在内存中存储所有双精度数据的方法。或者

    您知道如何扩展Java堆大小吗?如果没有,你需要学习——默认大小很小——只有64MB,如果内存可用的话(可以这么说)。从命令行,例如,为半个gig添加“-Xmx512m”:

    java -Xmx512m MyApp