将字符串转换为扩展的 ASCII 十进制

Convert String to Extended ASCII Decimal

使用我的程序,用户可以在 JTextfield 中键入文本。文本将保存在一个字符串中(在下面的代码中"strLine1")并且应该转换为十进制数。

因此我使用 getBytes。

bytearray1 = strLine1.getBytes();

这是我的输出代码:

for (int i=0; i<bytearray1.length; i++) {
                    builder1.append(bytearray1[i]);
                    if(i != bytearray1.length) 
                        builder1.append("• ");
}

这很好用,但是当我输入一些特殊字符如“ß”或“ö”时,我得到的输出如“-33”或“-10”。我读了很多,但没有取得成功。

“ß”的结果必须是 225,“ö”的结果必须是 148,如本页所示: http://www.theasciicode.com.ar/american-standard-code-information-interchange/ascii-codes-table.png

字符在那里列为 "extended ASCII"。

我也尝试了几个字符集,但没有得到正确的结果。

请帮忙。谢谢

使用 toCharArray() 而不是 getBytes()

我会把剩下的关于为什么的学习留给你。

好的,字节不能保存大于127的数字。没有提到。所以我将其更改为:

chararray1 = strLine1.toCharArray();

我的 Stringbuilder 的输出为:

builder1.append((int)chararray1[i]); 

但是“ß”是223而不是225。其他字符也是错误的。

所以我得到了一个对我很有效的解决方案:

我将其改回 getBytes 如下:

try {                                                   
                bytearray1 = strLine1.getBytes("CP858");
    }           catch (UnsupportedEncodingException e1) {
                e1.printStackTrace();
}

这里我使用的是正确的代码页 (858)。

这是我的输出:

for (int i=0; i<bytearray1.length; i++) {               
                    builder1.append((int)bytearray1[i] &0xff);      
                    if(i != bytearray1.length) 
                        builder1.append("• ");
                }
            }

因此“&0xff”将其从有符号转换为无符号。