Convert whole ByteBuffer to unsigned integer. - Java java.nio

Java examples for java.nio:ByteBuffer Convert

Description

Convert whole ByteBuffer to unsigned integer.

Demo Code

/*//  w ww.j ava 2  s  . co  m
 * WireSpider
 *
 * Copyright (c) 2015 kazyx
 *
 * This software is released under the MIT License.
 * http://opensource.org/licenses/mit-license.php
 */
//package com.java2s;
import java.nio.ByteBuffer;

public class Main {
    /**
     * Convert whole byte buffer to unsigned integer.
     *
     * @param bytes Source byte buffer.
     * @return The unsigned integer value.
     * @throws IllegalArgumentException Value exceeds int 32.
     */
    public static int toUnsignedInteger(ByteBuffer bytes) {
        long l = toUnsignedLong(bytes);
        if (Integer.MAX_VALUE < l) {
            // TODO support large payload over 2GB
            throw new IllegalArgumentException("Exceeds int32 range: " + l);
        }
        return (int) l;
    }

    /**
     * Convert whole byte buffer to long.
     *
     * @param bytes Source byte buffer.
     * @return The long value
     * @throws IllegalArgumentException Value exceeds int 64.
     */
    public static long toUnsignedLong(ByteBuffer bytes) {
        if (8 < bytes.remaining()) {
            throw new IllegalArgumentException("bit length overflow: "
                    + bytes.remaining());
        }
        long value = 0;
        for (byte b : bytes.array()) {
            value = (value << 8) + (b & 0xFF);
        }
        if (value < 0) {
            throw new IllegalArgumentException("Exceeds int64 range: "
                    + value);
        }
        return value;
    }
}

Related Tutorials