简体   繁体   English

Android:将文本输入转换为ASCII并将其打印为字符串

[英]Android: Convert Text Input to ASCII and print it as a string

This is my code 这是我的代码

EditText textExtract = (EditText) findViewById(R.id.textInput);
    String textInput = textExtract.getText().toString();
    TextView textOut = (TextView) findViewById(R.id.textOutput);

I am taking input from the user and storing it in String textInput . 我从用户那里获取输入并将其存储在String textInput中 Now, how do I convert the String textInput to a String of ASCII values which I want to print using the textView textOut. 现在,如何将String textInput转换为我想使用textView textOut打印的ASCII值字符串。

For example, 例如,

Input = "abcd"
Output = 979899100
public static long toAscii(String s){
    StringBuilder sb = new StringBuilder();
    String ascString = null;
    long asciiInt;
    for (int i = 0; i < s.length(); i++){
        sb.append((int)s.charAt(i));
        char c = s.charAt(i);
    }
    ascString = sb.toString();
    asciiInt = Long.parseLong(ascString);
    return asciiInt;
}



String outputText = toAscii(textInput).toString();
textOut.setText(outputText);

This could be helpful for your case 这可能对您的情况有所帮助

循环进入字符串,并将每个字符转换为Character.toString((char)i),将结果存储在数组中并将其作为字符串打印。

You can convert a character to ascii by casting the char to an int for example 例如,您可以通过将char转换为int来将字符转换为ascii

char c = 'A';
int ascii = (int) c;

To convert a whole string, iterate over the array of all chars. 要转换整个字符串,请遍历所有字符的数组。 You can get the Array using "Hello".getCharArray(); 您可以使用"Hello".getCharArray();来获取数组"Hello".getCharArray();

That would look like this: 这看起来像这样:

String input = "Hello World";
StringBuilder sb = new StringBuilder();
char[] chars = input.toCharArray();
for(char c : chars) 
    sb.append((int) c);
String output = sb.toString();

Here a StringBuilder is used to chain the single numbers together, which is better than using .concat() on Strings multiple times. 这里使用StringBuilder将单个数字链接在一起,这比在Strings上多次使用.concat()更好。

   String str = textView1.getText().toString();
    StringBuilder sb = new StringBuilder();
    for (char c : str.toCharArray())
        sb.append((int)c);
    BigInteger mInt = new BigInteger(sb.toString());
    textView2.setText(mInt.toString());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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