我想用16个十六进制值初始化一个unsigned char数组。但是,我似乎不知道如何正确初始化/访问这些值。当我试图直观地访问它们时,我根本没有任何价值。
这是我的输出
The program was run with the following command: 4
Please be a value! -----> p
Here's some plaintext
使用以下代码运行时
int main(int argc, char** argv)
{
int n;
if (argc > 1) {
n = std::stof(argv[1]);
} else {
std::cerr << "Not enough arguments\n";
return 1;
}
char buff[100];
sprintf(buff,"The program was run with the following command: %d",n);
std::cout << buff << std::endl;
unsigned char plaintext[16] =
{0x0f, 0xb0, 0xc0, 0x0f,
0xa0, 0xa0, 0xa0, 0xa0,
0x00, 0x00, 0xa0, 0xa0,
0x00, 0x00, 0x00, 0x00};
unsigned char test = plaintext[1]^plaintext[2];
std::cout << "Please be a value! -----> " << test << std::endl;
std::cout << "Here's some plaintext " << plaintext[3] << std::endl;
return 0;
}
作为背景,这是学校小组项目的一部分。我们最终试图实现Serpent密码,但继续被无符号的char数组绊倒。我们的项目规范说我们必须有两个函数来接受Java中的Byte数组。我假设C ++中最接近的亲戚是unsigned char []。否则我会使用矢量。在代码的其他地方,我实现了一个setKey函数,该函数接受一个unsigned char数组,将其值打包成4个long long int(密钥需要为256位),并对这些int执行各种位移和xor运算以生成密码算法所必需的密钥。希望有足够的背景来做我想做的事情。我猜我在这里只是忽略了一些基本的C ++功能。感谢您的帮助!
答案 0 :(得分:7)
char
是一个8位值,能够存储-128&lt; = n&lt; = +127,经常用于存储不同编码的字符表示,通常用于西方,罗马字母表安装 - char
用于表示ASCII或utf编码值的表示。 “编码”表示字符集中的符号/字母已分配数值。将周期表视为元素的编码,使'H'(氢)编码为1,锗编码为32.在ASCII(和UTF-8)表中,位置32表示我们称之为“空格”的字符。
在char值上使用operator <<
时,默认行为是假设您正在传递字符编码,例如ASCII字符代码。如果你这样做
char c = 'z';
char d = 122;
char e = 0x7A;
char f = '\x7a';
std::cout << c << d << e << f << "\n";
所有四项任务都是等效的。 'z'是char(122)
的快捷/句法糖,0x7A
是十六进制为122,'\ x7a'是一个转义,形成ascii字符,值为0x7a或122 - iez < / p>
许多新程序员出错的地方是他们这样做:
char n = 8;
std::cout << n << endl;
这不会打印“8”,它会在ASCII表的第8位打印ASCII字符。
想一想:
char n = 8; // stores the value 8
char n = a; // what does this store?
char n = '8'; // why is this different than the first line?
让我们回顾片刻:当您将120
存储在变量中时,可以代表ASCII字符'x'
,但最终存储的只是数值120
,简单明了。
具体来说:当您将122
传递给最终将使用它从使用Latin1,ISO-8859-1,UTF-8或类似编码的字符集中查找字体条目的函数时,{ {1}}表示120
。
在一天结束时,'z'
只是标准整数值类型之一,它可以存储值char
,它可以简单地提升为-128 <= n <= +127
,{{ 1}},short
或int
等等。
虽然通常用于表示字符,但它也经常被用作说“我只存储非常小的值”的方式(例如整数百分比)。
long
如果要打印数值,只需将其提升为其他值类型:
long long
或首选的C ++方式
int incoming = 5000;
int outgoing = 4000;
char percent = char(outgoing * 100 / incoming);
答案 1 :(得分:2)
我认为(你的问题并不完全清楚)答案就像这个
一样简单std::cout << "Please be a value! -----> " << static_cast<unsigned>(test) << std::endl;
如果要输出char或unsigned char的数值,则必须先将其强制转换为int或unsigned。
毫不奇怪,默认情况下,字符输出为字符而不是整数。
BTW这个时髦的代码
char buff[100];
sprintf(buff,"The program was run with the following command: %d",n);
std::cout << buff << std::endl;
更简单地写为
std::cout << "The program was run with the following command: " << n << std::endl;
答案 2 :(得分:0)
std::cout
和std::cin
始终将char变量视为字符
如果要输入或输出为int,则必须手动执行以下操作。
std::cin >> int_var; c = int_var;
std::cout << (int)c;
如果使用scanf或printf,则不存在格式参数(&#34;%d&#34;,&#34;%c&#34;,&#34;%s&#34;)的问题howto covert input buffer(integer,char,string)。