Java Binary Encode toBinary(int nr, int bits)

Here you can find the source of toBinary(int nr, int bits)

Description

to Binary

License

Open Source License

Declaration

public static String toBinary(int nr, int bits) 

Method Source Code

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

public class Main {
    public static String toBinary(int nr, int bits) {
        String binval = "";
        int val;
        int i = bits;
        do {/*from  ww w . j  a  va 2  s .c  om*/
            val = power(2, i);

            if (nr > val) {
                binval = binval + "1";
                nr = nr - val;

            } else {
                binval = binval + "0";
            }
            i--;

        } while (i > 0);
        return binval;
    }

    public static int power(int nr, int pwr) {
        int retval = 1;
        for (int i = 0; i < pwr; i++) {
            retval = retval * nr;
        }
        return retval;
    }
}

Related

  1. toBinary(final byte[] array, final int offset, final int length)
  2. toBinary(final byte[] bytes)
  3. toBinary(final double d)
  4. toBinary(final double d)
  5. toBinary(final Object o)
  6. toBinary(int number, int length)
  7. toBinary(int val)
  8. toBinary(int value, int bits)
  9. toBinary(long l, int bits)