Finds the position of a byte relative to the start of the buffer. - Java java.nio

Java examples for java.nio:ByteBuffer

Description

Finds the position of a byte relative to the start of the buffer.

Demo Code

/*/*from  w w  w  .ja v  a  2s.  co  m*/
 * Copyright (C) 2008-2010 Wayne Meissner
 *
 * This file is part of the JNR project.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
//package com.java2s;
import java.nio.ByteBuffer;

public class Main {
    /**
     * Finds the position of a byte relative to the start of the buffer.
     *
     * @param buf The ByteBuffer to find the value in
     * @param value The value to locate
     * @return The position within the buffer that value is found, or -1 if not
     * found.
     */
    public static int positionOf(ByteBuffer buf, byte value) {
        if (buf.hasArray()) {
            final byte[] array = buf.array();
            final int offset = buf.arrayOffset();
            final int limit = buf.limit();
            for (int pos = buf.position(); pos < limit; ++pos) {
                if (array[offset + pos] == value) {
                    return pos;
                }
            }

        } else {
            final int limit = buf.limit();
            for (int pos = buf.position(); pos < limit; ++pos) {
                if (buf.get(pos) == value) {
                    return pos;
                }
            }
        }

        return -1;
    }
}

Related Tutorials