0

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 ?

Murtaza Khursheed Hussain
  • 15,176
  • 7
  • 58
  • 83
Vid
  • 1,012
  • 1
  • 14
  • 29
  • Your code cannot compile. `Integer.toBinaryString()` expects an int as an argument, not a String – fge Feb 20 '15 at 14:47

3 Answers3

1

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);
    }
Murtaza Khursheed Hussain
  • 15,176
  • 7
  • 58
  • 83
1

Try what eznme suggests here:

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;
        }
    }
}
Community
  • 1
  • 1
Fahim
  • 12,198
  • 5
  • 39
  • 57
0

You try:

Long.toBinaryString(2199023255552L);

Java long to binary

Community
  • 1
  • 1