Interpret an int as its binary form - Java java.lang

Java examples for java.lang:int Binary

Description

Interpret an int as its binary form

Demo Code

/*//from ww w.j  av  a  2  s  .c om
 * 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 {
        int intValue = 2;
        System.out.println(java.util.Arrays.toString(fromInt(intValue)));
    }

    /**
     * Interpret an int as its binary form
     *
     * @param intValue The int to interpret to binary
     *
     * @return The binary
     */
    public static byte[] fromInt(int intValue) {
        byte[] bytes = new byte[4];
        bytes[0] = (byte) (intValue >> 24);
        bytes[1] = (byte) ((intValue << 8) >> 24);
        bytes[2] = (byte) ((intValue << 16) >> 24);
        bytes[3] = (byte) ((intValue << 24) >> 24);
        return bytes;
    }
}

Related Tutorials