假設在使用中設定的代碼不是EBCDIC(其具有在字母字符之間的非字母字符),則拉丁字母(重音A-Z)的字母被編碼爲在所有常見的代碼集的連續的代碼點。當你知道如何的時候,字母表的旋轉很簡單。
從根本上說,就轉換每個字母成從a
或A
(取決於情況)信偏移0..25,添加編碼密鑰,取結果的模26中,並添加起始字母(a
或A
)背部。請注意,算術運算爲int
,但結果被分配回(可能已簽名)char
。
#include <cs50.h>
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, string argv[])
{
if (argc != 2 || !isdigit((unsigned char)argv[1][0]))
{
fprintf(stderr, "Usage: %s shift\n", argv[0]);
return 1;
}
// convert input to int and get the string
int k = atoi(argv[1]) % 26;
if (k < 0)
k += 26;
char *s = GetString();
int n = strlen(s);
printf("Original: [%s]\n", s);
// encoding each character
for (int i = 0; i < n; i++)
{
if (isupper((unsigned char)s[i]))
{
s[i] = 'A' + (s[i] - 'A' + k) % 26;
}
else if (islower((unsigned char)s[i]))
{
s[i] = 'a' + (s[i] - 'a' + k) % 26;
}
}
printf("Encrypted: [%s]\n", s);
return 0;
}
實施例運行:
$ ./caesar13 3
Caesar's cipher is hardly secure against the lazy dog jumping over the quick brown fox, is it?
Original: [Caesar's cipher is hardly secure against the lazy dog jumping over the quick brown fox, is it?]
Encrypted: [Fdhvdu'v flskhu lv kdugob vhfxuh djdlqvw wkh odcb grj mxpslqj ryhu wkh txlfn eurzq ira, lv lw?]
$ ./caesar50 23
Fdhvdu'v flskhu lv kdugob vhfxuh djdlqvw wkh odcb grj mxpslqj ryhu wkh txlfn eurzq ira, lv lw?
Original: [Fdhvdu'v flskhu lv kdugob vhfxuh djdlqvw wkh odcb grj mxpslqj ryhu wkh txlfn eurzq ira, lv lw?]
Encrypted: [Caesar's cipher is hardly secure against the lazy dog jumping over the quick brown fox, is it?]
$
的CS50 library是現成的聯機。
當鍵是4時'z'和'Z'會發生什麼? –
歡迎來到Stack Overflow。請儘快閱讀[關於]頁面。 SO上有許多凱撒密碼實現的問題。他們大多會告訴你解決你的問題的方法。你真的看看(一些)他們。看起來你並沒有試圖解決這個問題 - 你只知道你已經掌握了它。你應該展示你的嘗試。 (此外,在某些時候,您必須決定如何處理數字和標點符號,此刻,您將它們視爲字母,這可能不是最佳選擇。) –
請在此代碼片段中查看: _http://ideone.com/QwOl1s_ –