0

Hi I am new to Java and any help would be appreciated I am trying to convert an decimal number into binary and then making a left shift on that binary number. But it does not allow me left shift on string and it gives me exception of I try to convert it to integer.

                int i = 40700;
                iToBinary = Integer.toBinaryString(i);
                i = Integer.parseInt(iToBinary);
                i=i<<1;

What should be the optimal way to do this. I also need to convert the decimal to binary with the sign magnitude so I don't think a direct function like toBinaryString would work for me. But I would like to know how to do this.

Kunj
  • 77
  • 9
  • While using shift operator there is always the risk of exceeding the integer limit. I think this has happened in your case. Please let me know if the answer I posted worked fine. – SamDJava Sep 16 '14 at 14:06

4 Answers4

0

The binary string you are parsing is to large for an integer. Try the following:

long i = 40700;
iToBinary = Long.toBinaryString(i);
i = Long.parseLong(iToBinary);
i=i<<1;
Grice
  • 1,345
  • 11
  • 24
0

This might be of help. Try

     int i = 40700;
     String iToBinary = Integer.toBinaryString(i<<1);
     Long z = Long.parseLong(iToBinary,2);
     System.out.println(" i " + z);

The answer we get is 81400

SamDJava
  • 267
  • 3
  • 13
0

You need additional parameter radix in parseInt method: see this link for example: How to convert a Binary String to a base 10 integer in Java

Here are java examples for this method:

Examples: 

     parseInt("0", 10) returns 0
     parseInt("473", 10) returns 473
     parseInt("+42", 10) returns 42
     parseInt("-0", 10) returns 0
     parseInt("-FF", 16) returns -255
     parseInt("1100110", 2) returns 102

In your case will be :

i = Integer.parseInt(iToBinary, 2);
Community
  • 1
  • 1
Nikola Dimitrovski
  • 720
  • 1
  • 10
  • 23
0

To solve your exception you can use the overloaded method of Integer.parseInt using two parameters, then you can define the radix.

Change this line:

i = Integer.parseInt(iToBinary);

To this:

i = Integer.parseInt(iToBinary, 2);
Bruno Franco
  • 2,028
  • 11
  • 20