Java Binary Encode toBinaryArray(int integer, int size)

Here you can find the source of toBinaryArray(int integer, int size)

Description

Converts an integer to a binary array with a specified max size input: 11, output: [1011]

License

Apache License

Parameter

Parameter Description
integer a parameter
size a parameter

Declaration

public static boolean[] toBinaryArray(int integer, int size) 

Method Source Code

//package com.java2s;
//License from project: Apache License 

public class Main {
    /**/*  w  w w  . j  ava 2  s .  com*/
     * Converts an integer to a binary array with a specified max size
     * input: 11, output: [1011]
     * @param integer
     * @param size
     * @return
     */
    public static boolean[] toBinaryArray(int integer, int size) {
        boolean[] b = new boolean[size];
        String s = Integer.toBinaryString(integer);
        if (s.length() > b.length)
            s = s.substring(s.length() - b.length);
        // algorithm bug fixed kmr jan 2012
        // the 1s place is at the end of the string, so start there
        for (int i = s.length() - 1; i >= 0; i--)
            // the 1s element is at b[0] so start there
            b[s.length() - 1 - i] = (s.charAt(i) == '1');
        return b;
    }
}

Related

  1. toBinary(long l, int bits)
  2. toBinary(long v, int len)
  3. toBinary(short value)
  4. toBinaryAddress(int index, int maxIndex)
  5. toBinaryArray(int input, int length)
  6. toBinaryBoolean(boolean source)
  7. toBinaryChar(boolean bit)
  8. toBinaryClassName(String fileName)
  9. toBinaryFromHex(byte ch)