java - 如何对字母表添加值进行简单的加密?
问题描述
解决方案
Well if it's just A-Z
that you care about, you can write a simple encryption function like so:
char encrypt(char letter){
char[] alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray();
char next_letter = alphabet[(letter - 'A' + 1) % 26];
return next_letter;
}
letter - 'A'
gives us the position of the letter in the alphabet array, for example if we wanted to get the position of 'C', 'C' - 'A' = 2
and the position of alphabet[2]
is indeed 'C'.
To get the next letter, we offset by 1, ie letter - 'A' + 1
The % 26
helps ensure we loop back to the beginning if we're at the end, ie when we're trying to encrypt 'Z' for example,
'Z' - 'A' + 1 = 26
26 % 26 = 0.
System.out.println(encrypt('Z'));
>>> A
Likewise, you could write a decrypt function like so:
char decrypt(char letter){
char[] alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray();
char prev_letter = alphabet[26 - (letter - 'A' + 1)];
return prev_letter;
}
推荐阅读
- java - SLF4j 记录器中的字符串是否消耗堆空间
- amazon-web-services - 主机名/IP 与证书的替代名称不匹配
- cockroachdb - 用于 sql 转储导入的 Cockroach DB 多租户 IMPORT 错误
- python - 覆盖在我的项目中找不到模块
- java - 如何访问 Akka Stream 的计算结果?
- erlang - Erlang:如何返回列表的元素?
- sql - 从一个表中选择,从另一个表中计数,WHRER
- python-3.x - 试图找出从列表中随机选择一个项目的逻辑,使用返回值从另一个列表中随机选择一个项目。Python
- html - 添加 schema.org 文章 - LOGO 问题
- spring-kafka - 在 Spring Cloud Stream 中反序列化时如何信任所有包?