Reputation: 1012
I am trying to convert int to binary and i am doing below code.
public static String intToBinary16Bit(String strInt) {
String bin = Integer.toBinaryString(strInt);
return String.format("%016d", Integer.parseInt(bin));
}
So, if i am giving strInt = 0211
than it is working fine and giving the output
0000001000010001
.
But, if i am giving strInt = 4527
than it is throwing NumberFormateException
.
How can I resolved this issue ?
Upvotes: 0
Views: 243
Reputation: 12358
public class A {
public static void main(String[] args) {
int a = Integer.parseInt(args[0]);
System.out.println(a);
int bit=1;
for(int i=0; i<32; i++) {
System.out.print(" "+(((a&bit)==0)?0:1));
bit*=2;
}
}
}
Upvotes: 1
Reputation: 15336
Try the following method, it uses recursion for conversion.
private static void toBinary(int number) {
int remainder;
if (number <= 1) {
System.out.print(number);
return;
}
remainder = number % 2;
toBinary(number >> 1);
System.out.println(remainder);
}
Upvotes: 1