Reputation: 25
I'm creating an android app that converts ascii to binary. But I can't figure out on how to access a string I made outside the for-loop. if I type in binary(var name) android studio gives me an error. Here's my code(it's only in the on-click listener)
String output = "";
String input = textEditText.getText().toString();
int length = input.length();
for (int i = 0;i < length;i++) {
char c = input.charAt(i);
int value = Integer.valueOf(c);
String binaryOutpt2 = Integer.toBinaryString(value);
String binary = output + binaryOutpt2;
}
Upvotes: 0
Views: 493
Reputation: 164089
Use StringBuilder
instead of String
for the variable output
, like this:
String input = textEditText.getText().toString();
StringBuilder output = new StringBuilder();
int length = input.length();
for (int i = 0; i < length; i++) {
char c = input.charAt(i);
int value = (int) c;
String s = Integer.toBinaryString(value);
for (int j = 0; j < 8 - s.length(); j++) {
output.append("0");
}
output.append(s);
}
String out = output.toString();
this way you append each binary value of each char at the initial output and finally you get the whole binary representation of the text.
Also pad zeroes at the start of each binary value until you get 8 binary digits for each char.
Upvotes: 3