Converts an integer into a 4-byte array. - Java java.lang

Java examples for java.lang:byte Array Convert

Description

Converts an integer into a 4-byte array.

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) throws Exception {
        int v = 2;
        System.out.println(java.util.Arrays.toString(toBytes(v)));
    }//from   w  ww  .  j  av  a 2s .  c om

    /**
     * Converts an integer into a 4-byte array. Most significant bit first.
     */
    public static byte[] toBytes(int v) {
        byte[] b = new byte[4];
        b[0] = (byte) ((v >>> 24) & 0xFF);
        b[1] = (byte) ((v >>> 16) & 0xFF);
        b[2] = (byte) ((v >>> 8) & 0xFF);
        b[3] = (byte) ((v >>> 0) & 0xFF);

        return b;
    }

    /**
     * Converts a long into a 8-byte array. Most significant bit first.
     */
    public static byte[] toBytes(long v) {
        byte[] b = new byte[8];
        b[0] = (byte) ((v >>> 56) & 0xFFL);
        b[1] = (byte) ((v >>> 48) & 0xFFL);
        b[2] = (byte) ((v >>> 40) & 0xFFL);
        b[3] = (byte) ((v >>> 32) & 0xFFL);
        b[4] = (byte) ((v >>> 24) & 0xFFL);
        b[5] = (byte) ((v >>> 16) & 0xFFL);
        b[6] = (byte) ((v >>> 8) & 0xFFL);
        b[7] = (byte) ((v >>> 0) & 0xFFL);

        return b;
    }
}

Related Tutorials