[英]How do I use ORD and CHR with only A to Z and 0 to 9?
我正在嘗試編寫一個Caesar密碼,但只使用大寫字母數字。 使用ord
或chr
使用整個ASCII表。 怎么能做到這一點?
這是我到目前為止:
alphabet = ['A'..'Z'] ++ ['0'..'9']
c2I = ord c - ord 'A'
i2C = chr (n + ord 'A')
基本的想法是使用mod
來包裝到開頭。
現在它效率不高(但是嘿,你使用的是最不安全的密碼所以你可能不在乎)但我會告訴你只使用字母和索引函數:
import Data.List (elemIndex)
alphabet :: [Char]
alphabet = ['A'..'Z'] ++ ['0'..'9']
ith :: Int -> Char
ith i = alphabet !! j
where j = i `mod` length alphabet
index :: Char -> Int
index c = case c `elemIndex` alphabet of
Just i -> i
Nothing -> error "not inalphabet"
encode :: Int -> String -> String
encode n xs = [ ith $ index x + n | x <- xs ]
這會給你
λ> encode 3 "ABCXYZ012789"
"DEF012345ABC"
現在你可能想要找到一種使用ord
和chr
- 如果你在AZ
和0-9
之間進行區分,兩者都有效,因為范圍是:
所以你不能采取一個公式,沒有很多技巧
你應該嘗試,但是這里的數學更多(你可能想要一些類似ord c - ord 'A'
代表字母而26 + ord c - ord '0'
代表數字首先得到它在0-35
范圍內。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.