简单的凯撒密码在java中 [英] Simple caesar cipher in java
本文介绍了简单的凯撒密码在java中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
嘿,我使用公式制作一个简单的凯撒密码[x->(x + shift-1)mod 127 + 1]我想让我的加密文本有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中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文