Hi, thanks for looking at this thread. :)

The goal:
I have this 2D boolean array (from my decoder thread). I managed to write a method that goes through the rows and appends a '1' or a '0' to a string based on what's in the array (1 for true, 0 for false).

The problem:
I get a string containing what I need - but how do I covert a String "0101" to an int 5?
I've tried parsing, casting and myString.getByte(); (and googling :) ).
I assume myString.getByte(); gets me close to the goal, however I can't seem to make that last step.

The code:

``````public String stringBin(boolean[][] table, int row, int col) {
String bin = null; // declare & initialize String
for (int i = red; i <= row; i++) { // locate row
for (int j = 0; j < col; j++) { // go cell by cell till end of column
if (table[i][j] == false) {
bin += '0'; // add 0 for false
} else {
bin += '1'; // add 1 for true
}
}
}
bin = bin.substring(4); // bin contains "null", so cut that off
return bin;
}
``````

## All 2 Replies

how do I covert a String "0101" to an int 5?

The conventional way is `Integer.parseInt("0101", 2)`.

If you want to learn how to do it yourself, then just go from left-to-right with a accumulator that starts at 0. For each digit you multiply the accumulator by 2 and then add the current digit.

`String.getBytes` is useless for this purpose. It will merely create an encoded `byte[]` for your string so you won't be able to access its characters correctly unless you know the code and can decode it.

If you don't want "null" in your string then why do you initialize `bin` to `null`?

Got it, thanks! :)

As for the null, for some reason I had to initialize the String before FOR loops.
It's no biggie, since "null" would always be on the same location - that one liner solved it. :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.