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.
Asked
Active
Viewed 4.7k times
3 Answers
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,308
- 14
- 26
-
-
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,761
- 19
- 49
- 78
-
The first line converts the binary integer to decimal and then parses it as binary. It if was correct it would do nothing, but it isn't correct. – user207421 Apr 02 '15 at 03:36
-
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,214
- 19
- 20
-
You forgot your **break;** statement in the code above. you'll add a 1 bit after every 0. – Phil Ives -Rain Everywhere Jun 26 '17 at 06:37