Interpret the binary representation of a long. - Java java.lang

Java examples for java.lang:int Binary

Description

Interpret the binary representation of a long.

Demo Code

/*/*from  w w w.  j  av  a  2s.  co m*/
 * Hibernate, Relational Persistence for Idiomatic Java
 *
 * License: GNU Lesser General Public License (LGPL), version 2.1 or later.
 * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
 */
//package com.java2s;

public class Main {
    public static void main(String[] argv) throws Exception {
        byte[] bytes = new byte[] { 34, 35, 36, 37, 37, 37, 67, 68, 69 };
        System.out.println(asLong(bytes));
    }

    /**
     * Interpret the binary representation of a long.
     *
     * @param bytes The bytes to interpret.
     *
     * @return The long
     */
    public static long asLong(byte[] bytes) {
        if (bytes == null) {
            return 0;
        }
        if (bytes.length != 8) {
            throw new IllegalArgumentException(
                    "Expecting 8 byte values to construct a long");
        }
        long value = 0;
        for (int i = 0; i < 8; i++) {
            value = (value << 8) | (bytes[i] & 0xff);
        }
        return value;
    }
}

Related Tutorials