Converts a 32-bit unsigned int to a 4-byte array - Java java.lang

Java examples for java.lang:byte Array Convert

Description

Converts a 32-bit unsigned int to a 4-byte array

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) throws Exception {
        long value = 2;
        System.out.println(java.util.Arrays.toString(fromUInt32(value)));
    }//ww  w. j av  a 2 s.  com

    /**
     * Converts a 32-bit unsigned int to a 4-byte array
     */
    public static byte[] fromUInt32(long value) {
        if (value > 4294967295l) {
            throw new IllegalArgumentException("Must be less than 2^32");
        }
        if (value < 0) {
            throw new IllegalArgumentException("Must be greater than 0");
        }
        byte[] bytes = new byte[4];
        bytes[3] = (byte) (value & 0xff);
        bytes[2] = (byte) ((value >> 8) & 0xff);
        bytes[1] = (byte) ((value >> 16) & 0xff);
        bytes[0] = (byte) ((value >> 24) & 0xff);
        return bytes;
    }

    /**
     * Print a byte array as a String
     */
    public static String toString(byte[] bytes) {

        StringBuilder sb = new StringBuilder(4 * bytes.length);
        sb.append("[");

        for (int i = 0; i < bytes.length; i++) {
            sb.append(unsignedByteToInt(bytes[i]));
            if (i + 1 < bytes.length) {
                sb.append(",");
            }
        }

        sb.append("]");
        return sb.toString();
    }

    /**
     * Convert an unsigned byte to an int
     */
    public static int unsignedByteToInt(byte b) {
        return (int) b & 0xFF;
    }
}

Related Tutorials