Convert whole ByteBuffer to long. - Java java.nio

Java examples for java.nio:ByteBuffer Convert

Description

Convert whole ByteBuffer to long.

Demo Code

/*/*from   w  w  w .j  a v a  2 s  .  com*/
 * 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 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