Java ByteBuffer Put putUnsignedShort(ByteBuffer bytes, int value)

Here you can find the source of putUnsignedShort(ByteBuffer bytes, int value)

Description

put Unsigned Short

License

Open Source License

Declaration

public static ByteBuffer putUnsignedShort(ByteBuffer bytes, int value) throws IOException 

Method Source Code


//package com.java2s;
/*/*www.j  ava  2  s.c om*/
Copyright 2011 Semantic Discovery, Inc. (www.semanticdiscovery.com)
    
This file is part of the Semantic Discovery Toolkit.
    
The Semantic Discovery Toolkit is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
    
The Semantic Discovery Toolkit is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU Lesser General Public License for more details.
    
You should have received a copy of the GNU Lesser General Public License
along with The Semantic Discovery Toolkit.  If not, see <http://www.gnu.org/licenses/>.
*/

import java.nio.ByteBuffer;
import java.io.IOException;

public class Main {
    public static ByteBuffer putUnsignedShort(ByteBuffer bytes, int value) throws IOException {
        if (bytes.remaining() < 2)
            throw new IOException("not enough space in buffer to write unsigned short");

        if (value > 65535)
            throw new IOException("int value exceeds maximum unsigned short value of 65535!");

        byte b1 = (byte) (0xff & (value >> 8));
        byte b2 = (byte) (0xff & value);

        bytes.put(b1);
        bytes.put(b2);

        return bytes;
    }

    public static ByteBuffer putUnsignedShort(ByteBuffer bytes, int pos, int value) throws IOException {
        if ((pos + 2) > bytes.limit())
            throw new IOException("not enough space in buffer to write unsigned short");

        if (value > 65535)
            throw new IOException("int value exceeds maximum unsigned short value of 65535!");

        byte b1 = (byte) (0xff & (value >> 8));
        byte b2 = (byte) (0xff & value);

        bytes.put(pos, b1);
        bytes.put(pos + 1, b2);

        return bytes;
    }
}

Related

  1. putUInt16(ByteBuffer buffer, long value)
  2. putUInt32(ByteBuffer buffer, long value)
  3. putUnsignedByte(ByteBuffer bb, int value)
  4. putUnsignedInt(ByteBuffer buffer, long value)
  5. putUnsignedInt(final ByteBuffer dst, final long value)
  6. putUUID(ByteBuffer bytes, UUID uuid)
  7. putVarint(ByteBuffer buffer, long number, int byteSize)
  8. putVInt(ByteBuffer b, int i)
  9. putWhatFits(ByteBuffer dest, ByteBuffer src)