Algo.Java.ConvertBinaryToInt.Theory

To convert a binary number to an integer mathematically, you can use the following formula:

Formula

Given a binary number bbb with digits bk,bk−1,…,b1,b0b_k, b_{k-1}, …, b_1, b_0bk​,bk−1​,…,b1​,b0​, where bib_ibi​ is the bit at position iii (0 for least significant bit), the integer value is:

Explanation

  • bib_ibi​ is the bit at position iii (0 or 1).
  • 2i2^i2i is the positional value of the bit in base-2 (binary).
  • The formula computes the weighted sum of all the bits, starting from the least significant bit (rightmost) at position i=0i = 0i=0 to the most significant bit (leftmost).

Example

Let’s take the binary number 101110111011:

  1. Label the positions of each bit:
    • b3=1,b2=0,b1=1,b0=1b_3 = 1, b_2 = 0, b_1 = 1, b_0 = 1b3​=1,b2​=0,b1​=1,b0​=1.
  2. Use the formula:Integer Value=b3⋅23+b2⋅22+b1⋅21+b0⋅20\text{Integer Value} = b_3 \cdot 2^3 + b_2 \cdot 2^2 + b_1 \cdot 2^1 + b_0 \cdot 2^0Integer Value=b3​⋅23+b2​⋅22+b1​⋅21+b0​⋅20
  3. Substitute the values:Integer Value=1⋅23+0⋅22+1⋅21+1⋅20\text{Integer Value} = 1 \cdot 2^3 + 0 \cdot 2^2 + 1 \cdot 2^1 + 1 \cdot 2^0Integer Value=1⋅23+0⋅22+1⋅21+1⋅20
  4. Calculate:Integer Value=8+0+2+1=11\text{Integer Value} = 8 + 0 + 2 + 1 = 11Integer Value=8+0+2+1=11

Generalization

For a binary number b=bkbk−1…b0b = b_k b_{k-1} \dots b_0b=bk​bk−1​…b0​:Integer Value=bk⋅2k+bk−1⋅2k−1+⋯+b0⋅20\text{Integer Value} = b_k \cdot 2^k + b_{k-1} \cdot 2^{k-1} + \dots + b_0 \cdot 2^0Integer Value=bk​⋅2k+bk−1​⋅2k−1+⋯+b0​⋅20

public static int binaryToInt(int[] binary) {
    int result = 0;
    for (int i = 0; i < binary.length; i++) {
        result += binary[binary.length - 1 - i] * Math.pow(2, i); // Apply the formula
    }
    return result;
}

// another example

    public static void main(String[] args) {
        int[] binary = {1, 0, 1, 1};
        int result = 0;

        for (int bit : binary) {
            result = result * 2 + bit;
        }

        System.out.println("The integer value is: " + result);
    }

// also we can just parse it from string

Integer.parseInt("101", 2);
This entry was posted in Без рубрики. Bookmark the permalink.