Converts a byte array that represents an unsigned 32-bit integer - Java java.lang

Java examples for java.lang:byte Array Convert

Description

Converts a byte array that represents an unsigned 32-bit integer

Demo Code


//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(getUInt32(bytes));
    }//  w w w.java 2  s  . c  o  m

    /**
     * Converts a byte array that represents an unsigned 32-bit
     * integer
     */
    public static long getUInt32(byte[] bytes) {
        if (bytes.length != 4) {
            throw new IllegalArgumentException("Must be 4 bytes");
        }
        long value = bytes[3] & 0xFF;
        value |= ((bytes[2] << 8) & 0xFF00);
        value |= ((bytes[1] << 16) & 0xFF0000);
        value |= (((bytes[0] & 0x7F) << 24) & 0xFF000000);
        if ((bytes[0] & 0x80) != 0) {
            value += 2147483647;
            value += 1;
        }
        if (value < 0) {
            throw new IllegalArgumentException("getUInt32 tried to return "
                    + value);
        }
        return value;

    }
}

Related Tutorials