How to Convert Binary String to Int in Java?

How to Convert Binary String to Int in Java?

Do you want to know how to convert a binary string to int in Java? 🤔

Binary is composed of the two digits 0 and 1, and it is used to encode various computer commands. However, it is challenging for people to read these binary codes. For this reason, there are several methods for transforming binary data into a format that humans can understand.

In this article, we will go through the two ways to convert a binary string to int in Java. The binary number will be taken and parsed in order to produce an int that represents the binary number. 

So without further ado, let’s dive deep into the topic and see some real examples!

 

 

How to Convert Binary String to Int in Java?

In Java, there are three solutions to convert a binary string to an int in Java, they are the following; 

  1. Using Integer.parseInt()
  2. Using Math.pow()
  3. Using custom logic
  4. Using BigInteger() Class

 

Method 1: Use Integer.parseInt()

Using the Integer.parseInt() function converts strings to integers. The following is the parseInt() method’s example:

 

Code

public class Binary_to_Int{  

public static void main(String args[]){  



String binaryInt="1110";  

int string=Integer.parseInt(binaryInt,2);  



System.out.println(" The integer value is " );  

System.out.println(string);

}

}

 

Output

The integer value is 14.

 

Integer.parseInt(), the first method, converts the supplied string into an int. Integer.parseInt() produces an int result that is computed using the radix number when we supply a string, The binary value in the example’s binaryInt object has to be changed into an int. The solution is parseInt (binary string, 2). Because a binary is a base-2 number system, the first parameter is the string, and the second argument is 2.

If you have a binary string in Java and you want to convert it to an integer, you can use the Integer.parseInt() function with the base parameter set to 2. Here’s an example of how to do this:

String binaryString = "1010";
int integerValue = Integer.parseInt(binaryString, 2);

System.out.println(integerValue); // Output: 10

 

This code converts the binary string “1010” to the integer value 10. The Integer.parseInt() function takes a string as its first argument, and the base (in this case, 2) as its second argument. It then returns the integer value represented by the string.

If the binary string is not a valid binary representation of an integer, the Integer.parseInt() function will throw a NumberFormatException. You can catch this exception and handle it as needed. For example:

try
{
  String binaryString = "1010";
  int integerValue = Integer.parseInt(binaryString, 2);

  System.out.println(integerValue); // Output: 10
}
catch (NumberFormatException e)
{
  System.out.println("Invalid binary string: " + binaryString);
}

 

By using the Integer.parseInt() function with the base parameter set to 2, you can easily convert a binary string to an integer in Java. This can be useful if you need to perform calculations on binary data, or if you need to convert binary strings to integers for other purposes.

 

Method 2: Using Math.pow()

We can also convert a binary string to an int in Java by using Math.pow() Method. Let’s see an example:

 

Code

public class Main {

    public static void main(String[] args) {


        String binarytoint = "10111100";

        double converted_Double = 0;



        for (int i = 0; i < binarytoint.length(); i++) {


            if (binarytoint.charAt(i) == '1') {

                int len = binarytoint.length() - 1 - i;

                converted_Double += Math.pow(2, len);

            }

        }


        int converted_Int = (int) converted_Double;

        System.out.println("The converted integer is ");

        System.out.println(converted_Int);

    }

}

 

Output

The converted integer is 188.

 

Every character must be looped through until the string is the desired length. The next step is to determine whether binarytoint has any 1s, as only 1s are added while converting from binary to decimal. If a 1, it will first reduce the length of binarytoint by 1 and by the value of the iteration. 

 

 

Method 3: Using custom logic

Using custom logic, we can convert multiple binary strings to an integer in Java.

 

Code

public class Binary_to_Int{    

public static int Decimal(int b){  

    int decimal = 0;  

    int n = 0;  

    while(true){  

      if(b == 0){  

        break;  

      } else {  

          int temp = b%10;  

          decimal += temp*Math.pow(2, n);  

          b = b/10;  

          n++;  

       }  

    }  

    return decimal;  

}  

public static void main(String args[]){    

System.out.println(" The Decimal of 11110 is: "+Decimal(1010));  

System.out.println("The Decimal of 10111 is:  "+Decimal(10101) );  

System.out.println("The Decimal of 10001 is: "+Decimal(11111));  

}}

 

Output

The Decimal of 11110 is: 10

The Decimal of 10111 is:  21

The Decimal of 10001 is: 31

 

In the above example, we have declared a variable “b,” and “if“ block executes when “b” is equal to zero or the “else” block executes, then b is converted to an int with the use of Math.pow function.

 

 

Method 4: Using BigInteger() Class

If you need to convert a binary string that is longer than 32 bits (the maximum size of an integer in Java), you can use the BigInteger class instead. This class can represent integers of any size, and it has a valueOf() method that you can use to convert a binary string to a BigInteger object. Here’s an example:

String binaryString = "110101010101010101010101010101010101010101010101010101010101010101";
BigInteger bigIntValue = new BigInteger(binaryString, 2);

System.out.println(bigIntValue); // Output: 81985529216486895

 

This code converts the binary string to a BigInteger object with the value 81985529216486895. The BigInteger class also has methods that you can use to perform calculations on the integer value, such as add(), subtract(), multiply(), and divide().

By using the BigInteger class, you can easily convert a binary string to a BigInteger object in Java, regardless of the size of the binary string. This can be useful if you need to perform calculations on large binary values, or if you need to store binary data that is larger than the maximum size of an integer.

It’s worth noting that there are also other ways to convert a binary string to an integer in Java. For example, you can use the Long.parseLong() function with the base parameter set to 2 to convert a binary string to a long integer, or you can use the Integer.valueOf() method with the base parameter set to 2 to convert a binary string to an Integer object. You can also use bitwise operators such as &, |, and << to manipulate the binary string and convert it to an integer.

 

 

Conclusion

Ultimately, the method you choose to convert a binary string to an integer in Java will depend on your specific needs and the requirements of your application. Regardless of which method you choose, you should now have a better understanding of how to convert a binary string to an integer in Java.

To summarize the article, we have discussed what a binary string in Java is and how to convert a Java binary string to an integer.  Furthermore, we’ve discussed the three methods to convert a binary string to an integer, which are the following: 

  1. Using Integer.parseInt()
  2. Using Math.pow()
  3. Using custom logic
  4. Using BigInteger() class

The easiest way to convert a Java binary string to an integer is to use the Integer.parseInt() method.

Let’s have a quick recap of the topics discussed in this article.

  1. What is a binary String in Java?
  2. The Integer.parseInt() method to convert a binary string into an integer.
  3. The Math.pow() method to convert a binary string to int in Java.
  4. The BigInteger() class to convert a binary string into an integer.
  5. Custom logic to convert a binary string to an integer.

If you’ve found this article helpful, comment below and let 👇 know which solutions have helped you solve the problem.

Total
0
Shares
Leave a Reply

Your email address will not be published. Required fields are marked *

Related Posts
Total
0
Share