如何获取用户输入(来自扫描仪)并将整个输入转换为ascii

时间:2016-03-23 10:02:33

标签: java ascii stringbuilder

我正在做一个小的java RSA加密任务,我发现自己陷入困境。

我目前正在使用一个字符串构建器,它接收用户输入并将其全部转换为ascii但是它只是给ascii的确切字符(a = 97)加密成可读的东西,它需要输出所有字符,如这(a = 097)。

任何想法如何解决这个问题还是有更好的解决方案?

 String Secret;

 Scanner input = new Scanner(System.in); //opens a scanner, keyboard
 System.out.println("Please Enter what you want to encrypt: "); //prompt the user
 Secret = input.next(); //store the input from the user

 String str = Secret;  // or anything else

 StringBuilder sb = new StringBuilder();// do 1 character at a time. / convert each to ascii one at a time and then, have each2 values equate to 11 digit or "value"
 for (char c : str.toCharArray( ))
 sb.append((byte)c);// bit array could be easier as this could make it difficult to decrypt

     BigInteger m = new BigInteger(sb.toString());

 System.out.println(m);

1 个答案:

答案 0 :(得分:0)

您正在寻找的是为整数添加前导零的

打印格式化字符串

您需要使用System.out.format而不是println。 format是具有以下签名的方法

public PrintStream format(Locale l, String format, Object... args)

或者,使用JDK 默认区域设置

public PrintStream format(String format, Object... args)

所以你可以这样写:

int a = 97;
System.out.format("%03d%n",a);   //  -->  "097"

但您也可以使用 C Style printf方法

 System.out.printf("%03d\n",a);   //  -->  "097"

这或多或少与:

相同
String aWithLeadingZeros =String.format("%03d",a); 
System.out.println(aWithLeadingZeros); //  -->  "097"

这是如何将每个ASCII代码格式化为带有前导零字符串的3位数字并将所有字符串添加到StringBuffer

String secret = "hello world!"; // or anything else B)
StringBuilder sb = new StringBuilder();
for (char c : secret.toCharArray()) {
    // int casting wrap the char value 'c' to the corresponding ASCII code
    sb.append(String.format("%03d",(int)c));                        
}
System.out.println(sb); // -> 104101108108111032119111114108100033
// 'H' is 104, 'e' is 101, 'l' is 108, and so on..