0

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;
}
2
  • 1
    what is the error? Please give us more infos Commented Nov 18, 2018 at 15:24
  • Have you learned "variable scope"? Commented Nov 18, 2018 at 15:32

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

OK that makes more sense now

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.