简体   繁体   中英

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()

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);
        }
    }
}

使用Integer.valueOf(String, int)方法:

Integer.valueOf('10101',2)

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

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

Ofcourse b is a binary String.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM