Java 拆分字节数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2253912/
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-08-13 05:16:55  来源:igfitidea点击:

Splitting a Byte array

javaarraysbytearraybyte

提问by Tara Singh

Is it possible to get specific bytes from a byte array in java?

是否可以从java中的字节数组中获取特定字节?

I have a byte array:

我有一个字节数组:

byte[] abc = new byte[512]; 

and i want to have 3 different byte arrays from this array.

我想从这个数组中得到 3 个不同的字节数组。

  1. byte 0-127
  2. byte 128-255
  3. byte256-511.
  1. 字节 0-127
  2. 字节 128-255
  3. 字节 256-511。

I tried abc.read(byte[], offset,length)but it works only if I give offset as 0, for any other value it throws an IndexOutOfboundsexception.

我试过了,abc.read(byte[], offset,length)但它只有在我将偏移量设置为 0 时才有效,对于任何其他值,它都会引发IndexOutOfbounds异常。

What am I doing wrong?

我究竟做错了什么?

采纳答案by tangens

You can use Arrays.copyOfRange()for that.

你可以用Arrays.copyOfRange()它。

回答by Bozho

Arrays.copyOfRange()is introduced in Java 1.6. If you have an older version it is internally using System.arraycopy(...). Here's how it is implemented:

Arrays.copyOfRange()在 Java 1.6 中引入。如果您有旧版本,它会在内部使用System.arraycopy(...). 这是它的实现方式:

public static <U> U[] copyOfRange(U[] original, int from, int to) {
    Class<? extends U[]> newType = (Class<? extends U[]>) original.getClass();
    int newLength = to - from;
    if (newLength < 0) {
        throw new IllegalArgumentException(from + " > " + to);
    }
    U[] copy = ((Object) newType == (Object)Object[].class)
        ? (U[]) new Object[newLength]
        : (U[]) Array.newInstance(newType.getComponentType(), newLength);
    System.arraycopy(original, from, copy, 0,
                     Math.min(original.length - from, newLength));
    return copy;
}

回答by Ron

You could use byte buffers as views on top of the original array as well.

您也可以使用字节缓冲区作为原始数组顶部的视图。