嘿,我正在使用公式 [x-> (x+shift-1) mod 127 + 1] 在 Java 中制作一个简单的凯撒密码,我希望我的加密文本具有除控制字符之外的 ASCII 字符(即从32-127).如何避免在加密文本中应用 0-31 的控制字符.谢谢.
Hey I'm making a simple caesar cipher in Java using the formula [x-> (x+shift-1) mod 127 + 1] I want to have my encrypted text to have the ASCII characters except the control characters(i.e from 32-127). How can I avoid the control characters from 0-31 applying in the encrypted text. Thank you.
这样的事情怎么样:
public String applyCaesar(String text, int shift)
{
char[] chars = text.toCharArray();
for (int i=0; i < text.length(); i++)
{
char c = chars[i];
if (c >= 32 && c <= 127)
{
// Change base to make life easier, and use an
// int explicitly to avoid worrying... cast later
int x = c - 32;
x = (x + shift) % 96;
if (x < 0)
x += 96; //java modulo can lead to negative values!
chars[i] = (char) (x + 32);
}
}
return new String(chars);
}
诚然,这将 127 视为非控制字符,但实际上并非如此……您可能希望对其进行调整以保持范围为 [32, 126].
Admittedly this treats 127 as a non-control character, which it isn't... you may wish to tweak it to keep the range as [32, 126].
这篇关于java中的简单凯撒密码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!