getting 2 unsigned bytes from ByteBuffer. - Java java.nio

Java examples for java.nio:ByteBuffer

Description

getting 2 unsigned bytes from ByteBuffer.

Demo Code


//package com.java2s;

import java.nio.ByteBuffer;

public class Main {
    /**/*from ww w  .  ja v  a2  s.  c o m*/
     * This is a relative method for getting 2 unsigned bytes.  Unlike
     * {@link ByteBuffer#getShort()}, this method won't do sign-extension.
     *
     * @param buf The {@link ByteBuffer} to get bytes from.
     * @return Returns an unsigned integer in the range 0-65536.
     * @throws BufferUnderflowException if there are fewer than two bytes
     * remaining in the buffer.
     */
    public static int getUnsignedShort(ByteBuffer buf) {
        return buf.getShort() & 0x0000FFFF;
    }

    /**
     * This is an absolute method for getting 2 unsigned bytes.  Unlike
     * {@link ByteBuffer#getShort(int)}, this method won't do sign-extension.
     *
     * @param buf The {@link ByteBuffer} to get bytes from.
     * @param offset The absolute offset within the {@link ByteBuffer} of the
     * first byte to read; must be non-negative.
     * @return Returns an unsigned integer in the range 0-65536.
     * @throws IllegalArgumentException if the offset is either negative or
     * beyond the buffer's limit minus 1.
     */
    public static int getUnsignedShort(ByteBuffer buf, int offset) {
        try {
            return buf.getShort(offset) & 0x0000FFFF;
        } catch (IndexOutOfBoundsException e) {
            throw new IllegalArgumentException(e);
        }
    }
}

Related Tutorials