Vid
Vid

Reputation: 1012

How to convert big int number to Binary ? - Java

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

Answers (3)

Fahim
Fahim

Reputation: 12358

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;
        }
    }
}

Upvotes: 1

Murtaza Khursheed Hussain
Murtaza Khursheed Hussain

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

L&#234; Đức Anh
L&#234; Đức Anh

Reputation: 1

You try:

Long.toBinaryString(2199023255552L);

Java long to binary

Upvotes: 0

Related Questions