Top community members
All Wiki Articles Create Wiki Article

Many years me and my friends we were volunteers on my university doing programming classes for young people.

I got main conclusion: Young people are awesome, especially students, because they always bring new and fresh ideas :)
* I loved to do it but my time is limited

  I decided to create something that will help millions of students

Now I am here

co-founder

Java - convert binary String to int

0 contributions
5 points

Short solution:

String binaryString = "101";
int number = Integer.parseInt(binaryString, 2);

System.out.println(number); // 5

The best way to convert binary String to int in java is to useĀ Integer.parseInt() method.

Syntax:

Integer.parseInt(String binaryString, int radix)

1. Simple example

public class Example1 {

    public static void main(String[] args) {

        String binaryString = "101";
        int number = Integer.parseInt(binaryString, 2);
        System.out.println(number); // 5
    }
}

Output:

5

2. Convert couple of different binary strings to int

public class Example2 {

    public static void main(String[] args) {

        System.out.println( Integer.parseInt("00000000", 2) ); // 0
        System.out.println( Integer.parseInt("00000101", 2) ); // 5
        System.out.println( Integer.parseInt("00001000", 2) ); // 8
        System.out.println( Integer.parseInt("00001100", 2) ); // 12
        System.out.println( Integer.parseInt("00010000", 2) ); // 16
        System.out.println( Integer.parseInt("11111111", 2) ); // 255
    }
}

Output:

0
5
8
12
16
255

3. ConvertĀ binary string to int in loop - from 0 to 16

In this example we convert binary string to int in loop from 0 to 16 and then we print both binary and decimal representations of given number.

public class Example3 {

    public static void main(String[] args) {

        for (int number = 0; number <= 16; number++) {

            String binaryString = Integer.toBinaryString(number);

            String format = String.format("%8s", binaryString);
            String withLeadingZeros = format.replace(' ', '0');

            int backToNumber = Integer.parseInt(binaryString, 2);

            System.out.println(withLeadingZeros + " - " + backToNumber);
        }
    }
}

Output:

00000000 - 0
00000001 - 1
00000010 - 2
00000011 - 3
00000100 - 4
00000101 - 5
00000110 - 6
00000111 - 7
00001000 - 8
00001001 - 9
00001010 - 10
00001011 - 11
00001100 - 12
00001101 - 13
00001110 - 14
00001111 - 15
00010000 - 16

Ā 

0 contributions

Checkout latest Findings & News:

Checkout latest questions:

Checkout latest wiki articles:

Hey šŸ‘‹
Would you like to know what we do?
  • Dirask is IT community, where we share coding knowledge and help each other to solve coding problems.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.
Read more