programing

Java의 ByteBuffer에서 바이트 배열을 가져옵니다.

itsource 2022. 11. 3. 22:16
반응형

Java의 ByteBuffer에서 바이트 배열을 가져옵니다.

ByteBuffer에서 바이트를 가져오는 권장 방법입니까?

ByteBuffer bb =..

byte[] b = new byte[bb.remaining()]
bb.get(b, 0, b.length);

네가 뭘 하고 싶은지에 달렸어.

필요한 것이 나머지 바이트(위치와 제한 사이)를 취득하는 경우, 가지고 있는 바이트가 기능합니다.다음 작업을 수행할 수도 있습니다.

ByteBuffer bb =..

byte[] b = new byte[bb.remaining()];
bb.get(b);

이는 ByteBuffer javadocs와 동일합니다.

bb.array()는 바이트 버퍼의 위치를 지원하지 않으며, 작업 중인 바이트 버퍼가 다른 버퍼의 슬라이스일 경우 더 나빠질 수 있습니다.

예.

byte[] test = "Hello World".getBytes("Latin1");
ByteBuffer b1 = ByteBuffer.wrap(test);
byte[] hello = new byte[6];
b1.get(hello); // "Hello "
ByteBuffer b2 = b1.slice(); // position = 0, string = "World"
byte[] tooLong = b2.array(); // Will NOT be "World", but will be "Hello World".
byte[] world = new byte[5];
b2.get(world); // world = "World"

그게 네가 의도한 게 아닐 수도 있어.

바이트 배열을 복사하지 않을 경우 회피책으로 바이트 버퍼의 arrayOffset() + remaining()을 사용할 수 있지만 이는 응용 프로그램이 필요한 바이트 버퍼의 인덱스 + 길이를 지원하는 경우에만 작동합니다.

그것처럼 간단해.

  private static byte[] getByteArrayFromByteBuffer(ByteBuffer byteBuffer) {
    byte[] bytesArray = new byte[byteBuffer.remaining()];
    byteBuffer.get(bytesArray, 0, bytesArray.length);
    return bytesArray;
}
final ByteBuffer buffer;
if (buffer.hasArray()) {
    final byte[] array = buffer.array();
    final int arrayOffset = buffer.arrayOffset();
    return Arrays.copyOfRange(array, arrayOffset + buffer.position(),
                              arrayOffset + buffer.limit());
}
// do something else

지정된 내부 상태에 대해 아무것도 모르는 경우(Direct)ByteBuffer를 사용하여 버퍼의 콘텐츠 전체를 취득합니다.이거는 다음과 같이 사용할 수 있습니다.

ByteBuffer byteBuffer = ...;
byte[] data = new byte[byteBuffer.capacity()];
((ByteBuffer) byteBuffer.duplicate().clear()).get(data);

이 방법은 간단한 방법으로byte[], 단, 를 사용하는 포인트의 일부입니다.ByteBuffer를 작성할 필요가 없어집니다.byte[]아마도 당신은 당신이 원하는 것을 얻을 수 있을 것이다.byte[]에서 직접ByteBuffer.

언급URL : https://stackoverflow.com/questions/679298/gets-byte-array-from-a-bytebuffer-in-java

반응형