【问题标题】:ByteBuffer to int array (each byte)ByteBuffer 到 int 数组(每个字节)
【发布时间】:2015-02-15 10:44:08
【问题描述】:

与问题 byte array to Int Array 相关,但是我想将每个字节转换为 int,而不是每个 4 字节。

有没有比这更好/更清洁的方法:

protected static int[] bufferToIntArray(ByteBuffer buffer) {
    byte[] byteArray = new byte[buffer.capacity()];
    buffer.get(byteArray);

    int[] intArray = new int[byteArray.length];

    for (int i = 0; i < byteArray.length; i++) {
        intArray[i] = byteArray[i];
    }

    return intArray;
}

【问题讨论】:

    标签: java arrays


    【解决方案1】:

    我可能更喜欢

    int[] array = new int[buffer.capacity()];
    for (int i = 0; i < array.length; i++) {
      array[i] = buffer.get(i);
    }
    return array;
    

    【讨论】:

      【解决方案2】:

      对于 kotlin 程序员..

      fun getIntArray(byteBuffer: ByteBuffer): IntArray{
          val array = IntArray(byteBuffer.capacity())
          for (i in array.indices) {
              array[i] = byteBuffer.getInt(i)
          }
          return array
      }
      

      【讨论】:

        【解决方案3】:

        这会产生一个 int 数组:

        int[] intArray = byteBuffer.asInBuffer().array()

        【讨论】:

        • 但它不适用于 JDK,它会抛出 UnsupportedOperationException。 asIntBuffer() 创建一个视图,但array() 需要由可访问数组支持的东西才能工作。但是,此方法适用于 Android。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-01-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-07-31
        相关资源
        最近更新 更多