ASCII (American Standard Code for Information Interchange):美国信息交换标准代码是基于拉丁字母的一套电脑编码系统,主要用于显示现代英语和其他西欧语言。它是最通用的信息交换标准,并等同于国际标准 ISO/IEC 646。ASCII第一次以规范标准的类型发表是在1967年,最后一次更新则是在1986年,到目前为止共定义了128个字符。
更多请见百度百科
文章提供了一种方法,输入明文出密文和输入密文出明文。
目录
代码部分
import Foundation
// 加密函数
func encryptASCII(_ plaintext: String) -> String {
var ciphertext = ""
for char in plaintext {
let asciiValue = Int(char.asciiValue!)
let encryptedChar = String(asciiValue)
ciphertext += encryptedChar
}
return ciphertext
}
// 解密函数
func decryptASCII(_ ciphertext: String) -> String {
var plaintext = ""
var currentIndex = ciphertext.startIndex
while currentIndex < ciphertext.endIndex {
let currentChar = ciphertext[currentIndex]
if let asciiValue = UInt8(String(currentChar)) {
let decryptedChar = Character(UnicodeScalar(asciiValue))
plaintext += String(decryptedChar)
}
currentIndex = ciphertext.index(after: currentIndex)
}
return plaintext
}
// 输入
print("请选择操作:")
print("1. 加密")
print("2. 解密")
if let operation = readLine(), let operationInt = Int(operation) {
switch operationInt {
case 1:
print("请输入要加密的文本:")
if let plaintext = readLine() {
let ciphertext = encryptASCII(plaintext)
print("\n加密后的文本:\(ciphertext)")
}
case 2:
print("请输入要解密的文本:")
if let ciphertext = readLine() {
let plaintext = decryptASCII(ciphertext)
print("解密后的文本:\(plaintext)")
}
default:
print("无效的值")
}
}
// 判断
else{
print("无效的值或不存在")
}
实操部分
下面是实例:
注意事项
1. 如果在开始选择加密或者解密的时候输入无效的值则会反馈: