[英]Encrypt Digit C++
因此,我试图通过将数字加7,然后将整个数字除以10来加密四位整数。 在我的程序中,我将每个数字分别取一,然后将整个数字除以十。 如何将所有单独的int合并为一个四位数的数字?
#include "stdafx.h"
using namespace std;
int main()
{
//Define all variables needed
int a,b,c,d,enc,ext;
//Print dialog and input each single digit for the four number digit
cout << "Enter Your First Digit:" << endl;
cin >> a;
cout << "Enter Your Second Digit:" << endl;
cin >> b;
cout << "Enter Your Third Digit:" << endl;
cin >> c;
cout << "Enter Your Fourth Digit:" << endl;
cin >> d;
//Add seven to each digit
a += 7;
b += 7;
c += 7;
d += 7;
a /= 10;
b /= 10;
c /= 10;
d /= 10;
cout << "Your encrpyted digits:" << c << d << a << b <<endl;
cout << "Enter 1 to exit:" <<endl;
cin >> ext;
if (ext = 1) {
exit(EXIT_SUCCESS);
}
}
您可能已经注意到,我将每个数字分开。 我需要一起做 然后,我还要创建一个解密程序,然后在单独的程序中将其恢复为原始编号。
根据您的评论,您尝试对Caesar Cipher进行变体,在这种情况下,您应该使用模数运算符( %
)而不是整数除法运算符( /
)。 使用整数除法会丢失信息,这将使您无法解密。 当数字位于{0,1,2}中时,除法结果为0。当数字位于{3,4,5、6、7、8、9}中时,除法结果为1。将{0,1}解密回原始编号,而无需一些其他信息(已丢弃)。
如果要使用凯撒密码方法逐位加密,则应使用模运算,以便每个数字都有一个唯一的加密值,该值可以在解密期间取回。 如果这确实是您想要的,那么您应该执行以下类似的操作以使用7进行加密:
a = (a + 7) % 10;
b = (b + 7) % 10;
c = (c + 7) % 10;
d = (d + 7) % 10;
要递减,您要减去7,在mod 10算术中是3的加法,因此将是:
a = (a + 3) % 10;
b = (b + 3) % 10;
c = (c + 3) % 10;
d = (d + 3) % 10;
当然,这前提是您已经正确验证了您的输入(上面的示例中不是这种情况)。
这可能是您想要的:
int e = (a*1000)+(b*100)+(c*10)+d;
e=e/10;
将各个数字组合成一个四位数的数字很简单; 只需将第一个数字乘以1000,然后将第二个数字乘以100,依此类推。
但是,这是一种单向算法。 您将永远无法从中检索原始的四位数号码。
根据您的描述,不清楚该加法是否应取模10。 如果是这样的话
((((((a % 10) * 10) + (b % 10)) * 10) + (c % 10)) * 10) + (d % 10)
如果您不希望取模10
(((((a * 10) + b) * 10) + c) * 10) + d
撇开您几乎肯定要使用mod而不是除法这一事实(如@Andand所说),有多种方法可以将数字转换为数字!
如今,许多使用解释型语言的人可能想象征性地做到这一点。 实际上,C ++也可以做到这一点:
// create a string stream that you can write to, just like
// writing to cout, except the results will be stored
// in a string
stringstream ss (stringstream::in | stringstream::out);
// write the digits to the string stream
ss << a << b << c << d;
cout << "The value stored as a string is " << ss.str() << endl;
// you can also read from a string stream like you're reading
// from cin. in this case we are reading the integer value
// that we just symbolically stored as a character string
int value;
ss >> value;
cout << "The value stored as an integer is " << value << endl;
在这种狭窄的4位数字情况下,由于往返于字符串并返回,因此效率不如乘法。 但是很高兴知道这项技术。 这也是一种编码风格,可以更轻松地维护和适应。
如果#include <sstream>
则将得到stringstream。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.