Joedie 123
Joedie 123

Reputation: 365

Converting String binary to integer

How can I do this without using multiplication, division or mod?

I come with the solution but it needs multiplication.

public StringBToInt(String b) {
    int value = 0;
    for(int z = 0; z < b.length(); z++) {
        value = value * 2 + (int)b.charAt(i) - 48;
    }
}

EDIT: SORRY! Only 3 java API are allowed. length(), charAt(), and equals()

Upvotes: 1

Views: 121

Answers (4)

codecubed
codecubed

Reputation: 780

You can use the method Integer.parseInt to do this.

String binary = "101010"
int value = Integer.parseInt(binary, 2);

The '2' in Integer.parseInt means to parse the String in base 2.

Upvotes: 0

Abdelhak
Abdelhak

Reputation: 8387

Try to use Integer.parseInt(..) like this:

  int value = Integer.parseInt(b, 2);

Ofcourse b is a binary String.

Upvotes: 1

Matteo Di Napoli
Matteo Di Napoli

Reputation: 577

Without multiplication, use bitwise shift operator:

public StringBToInt(String b) {
    int value = 0;
    for(int z = 0; z < b.length(); z++) {
        if(b.charAt(z) == '1'){
            shift = b.length()-z-1;
            value += (1 << shift);
        }
    }
}

Upvotes: 2

cjstehno
cjstehno

Reputation: 13984

Use the Integer.valueOf(String, int) method:

Integer.valueOf('10101',2)

Upvotes: 1

Related Questions