12

What is the easiest way in java to get the binary representation of an integer as a binary number with a fixed number of bits (For example, if I want to convert 3 with 5 bits, then the result would be 00011). In matlab, I can just specify the number of bits as an argument.

giulio
  • 629
  • 2
  • 7
  • 20
  • 3
    [Left padding a String with zeros](http://stackoverflow.com/questions/4469717/left-padding-a-string-with-zeros) might help solve this, along with `Integer.toBinaryString(int)`. – Obicere Apr 02 '15 at 03:19

3 Answers3

12

This is a simple way:

String binaryString = Integer.toBinaryString(number);
binaryString = binaryString.substring(binaryString.length() - numBits);

Where number is the integer to convert and numBits is the fixed number of bits you are interested in.

alfreema
  • 1,125
  • 11
  • 23
  • But... I have "String index out of range: -3" in this case... – Line Jun 29 '17 at 13:41
  • Then you may want: binaryString = binaryString.substring(binaryString.length() - numBits >= 0 ? binaryString.length() - numBits : 0); – alfreema Jun 30 '17 at 02:56
9

If you want to convert an int into its binary representation, you need to do this:

String binaryIntInStr = Integer.toBinaryString(int);

If you want to get the bit count of an int, you need to do this:

int count = Integer.bitCount(int);

But you couldn't get the binary representation of an integer as a binary number with a fixed number of bits , for example, 7 has 3 bits, but you can't set its bit count 2 or 1. Because you won't get 7 from its binary representation with 2 or 1 bit count.

SilentKnight
  • 13,063
  • 18
  • 46
  • 76
3

To convert n to numbOfBits of bits:

public static String intToBinary (int n, int numOfBits) {
   String binary = "";
   for(int i = 0; i < numOfBits; ++i, n/=2) {
      switch (n % 2) {
         case 0:
            binary = "0" + binary;
         break;
         case 1:
            binary = "1" + binary;
         break;
      }
   }

   return binary;
}
hudsonb
  • 2,014
  • 18
  • 19