Java Binary Encode toBinaryAddress(int index, int maxIndex)

Here you can find the source of toBinaryAddress(int index, int maxIndex)

Description

Returns index as a binary string.

License

Open Source License

Parameter

Parameter Description
index a parameter
maxIndex a parameter

Declaration

public static String toBinaryAddress(int index, int maxIndex) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

public class Main {
    /**/*from  w  w w. j  av a 2 s .co m*/
     * Returns <code>index</code> as a binary string. <br>
     * The string is padded with zeros to the left such that its length would equal the minimal
     * length of the binary string representing <code>maxIndex</code>. <br>
     * Both integers are interpreted as unsigned values, therefore negative <code>int</code> values
     * will always assume a width of 32 characters.
     * 
     * @param index
     * @param maxIndex
     * @return
     */
    public static String toBinaryAddress(int index, int maxIndex) {
        int digits = Math.max(32 - Integer.numberOfLeadingZeros(maxIndex), 1);

        char[] buffer = new char[digits];
        int mask = 1;
        for (int i = digits - 1; i >= 0; i--) {
            buffer[i] = (index & mask) != 0 ? '1' : '0';
            mask <<= 1;
        }

        return new String(buffer);
    }
}

Related

  1. toBinary(int val)
  2. toBinary(int value, int bits)
  3. toBinary(long l, int bits)
  4. toBinary(long v, int len)
  5. toBinary(short value)
  6. toBinaryArray(int input, int length)
  7. toBinaryArray(int integer, int size)
  8. toBinaryBoolean(boolean source)
  9. toBinaryChar(boolean bit)