Reputation: 21
I have a program that transforms decimal number into a binary number. I want the binary representation to have 32 digits, so I often need to add 0 at the beginning of the binary representation. How can I achieve it?
Example:
decimal:
9999999
binary:
00000000 01001100 01001011 00111111
This is the code I already have: Code:
class Binaer {
public static void main(String [] args) {
java.util.Scanner scanner = new java.util.Scanner(System.in);
long a = scanner.nextLong();
while ( a != 0) {
System.out.println(Integer.toBinaryString(a));
}
}
}
Upvotes: 0
Views: 1112
Reputation: 2672
First, if you use Integer.toBinaryString(a), then a must be an Integer. Then, you can pad the received String using String.format:
number = Integer.toBinaryString(a);
paddedNumber = String.format("%32s", number).replace(' ', 0);
format will ensure paddedNumber has 32 signs by adding spaces at the beginning, if necessary. Then replace will replace spaces with '0' signs.
Upvotes: 0
Reputation: 61158
Easy, simply use String.format
:
public static void main(String[] args) throws InterruptedException {
final int i = 7;
final String s = String.format("%32s", Integer.toBinaryString(i)).replace(' ', '0');
System.out.println(s);
}
The first bit - String.format("%32s", Integer.toBinaryString(i))
- formats the int
as a binary String
which is padded from the start to 32 characters. The second bit - replace(' ', '0')
- replaces the leading spaces with zeros.
Upvotes: 2
Reputation: 16067
You can use String.format
or a StringBuilder
:
java.util.Scanner scanner = new java.util.Scanner(System.in);
int a = scanner.nextInt();
StringBuilder sb = new StringBuilder();
for(int i = 0; i < Integer.numberOfLeadingZeros(a); i++)
sb.append('0');
sb.append(Integer.toBinaryString(a));
System.out.println(sb.toString());
Upvotes: 0