Conversion of ASCII code to characters does not work

Asked

Viewed 1,290 times

1

First of all, I’m new to developing Android. I would like to know why my application hangs when I try to convert ASCII code to characters.

private String crip(String str, String psw) {
    int code = 0;
    String full_word="";
    for (int i= 0; i <= str.length(); i++) {
        code=(int)str.charAt(i); // Crashes aqui (eu acho)
        full_word+=code;
    }
    return full_word;
}

And at the onClick event:

crip.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View v) {
        if (!psw.getText().toString().isEmpty() && !str.getText().toString().isEmpty()) {
            out.setText(crip(str.getText().toString(), psw.getText().toString()));
        }

    }
});

There’s something wrong?

  • 1

    You are using setOnClickListener in a method that returns a string???

  • You need to debug your code. See what value the expression (int)str.charAt(i) has when the problem happens.

  • Please note that String is a sequence of UTF-16, not ASCII. The most important difference is that any ASCII sequence is valid, but there are UTF-16 sequences that are not -- it is not possible to reorganize or do arithmetic with UTF-16 characters arbitrarily.

1 answer

3


My Java is very weak, but I see a problem here:

for (int i= 0; i <= str.length(); i++)

You are iterating an extra character. The code should be:

for (int i= 0; i < str.length(); i++)
  • Whether or not this is the problem of OP, this in itself causes an error. Well noted!

  • If that alone solves his problem, there is another potential: the name of the method and the parameters implies that he is trying to hash a password or something, using ASCII codes. I don’t think it’s a good one, but it’s not my field either...

  • And in addition, the variable psw is not used

Browser other questions tagged

You are not signed in. Login or sign up in order to post.