Java ByteBuffer search for byte array from offset

Description

Java ByteBuffer search for byte array from offset

import java.nio.ByteBuffer;
import java.util.Arrays;

public class Main {
  public static void main(String[] argv) throws Exception {
    ByteBuffer bb = ByteBuffer.wrap("demo2s.com".getBytes());

    System.out.println(Arrays.toString(toArray(bb)));
    bb.flip();/* ww w  .j  a  v a2  s .  c o m*/
    int index = indexOf(bb, 0, (byte) 111);
    System.out.println(index);
    
    // bb.flip();
    index = indexOf(bb, 5, (byte) 111);
    System.out.println(index);
  }

  public static int indexOf(ByteBuffer buf, int offset, byte value) {
  
      int begin = buf.position();
      for (int idx = offset; idx < buf.limit(); ++idx) {
        if (buf.get(begin + idx) == value) {
          return idx;
        }
      }
  
    return -1;
  }

  public static byte[] toArray(final ByteBuffer buffer) {
    byte[] array = new byte[buffer.limit()];
    buffer.get(array);
    return array;
  }
}



PreviousNext

Related