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

How to take a user input (from scanner) and convert the entire input into ascii

我正在做一个小的 java RSA 加密任务,但我发现自己卡住了。

我目前正在使用一个 stringbuilder,它接受用户输入并将其全部转换为 ascii,但是它只是给出了准确的字符 (a = 97),以便将 ascii 加密成可读的东西,它需要输出所有像这样的字符 (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);

您正在寻找的是为您的整数打印一个带前导零的格式化字符串

您需要使用 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 风格 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..