Simple caesar cipher in java(java中的简单凯撒密码)
问题描述
嘿,我正在使用公式 [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中的简单凯撒密码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:java中的简单凯撒密码
基础教程推荐
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- Struts2 URL 无法访问 2022-01-01
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01
- RabbitMQ:消息保持“未确认"; 2022-01-01
- 修改 void 函数的输入参数,然后读取 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- 存储 20 位数字的数据类型 2022-01-01
