用c++程序以不同的基数输出不可打印字符
Output non-printable characters in different bases with a C++ program?
我认为这是一个简单的问题。我正在摆弄crypto++ lib和我在SO上找到的样本。因此,我试图在"转储密文"部分计算文本/ASCII字符(而不是十六进制)。
本部分(原):
//
// Dump Cipher Text
//
std::cout << "Cipher Text (" << ciphertext.size() << " bytes)" << std::endl;
for( int i = 0; i < ciphertext.size(); i++ ) {
std::cout << "0x" << std::hex << (0xFF & static_cast<byte>(ciphertext[i])) << " ";
}
std::cout << std::endl << std::endl;
我注意到一些奇怪的事情…在我尝试这样做之后,ciphertext.size()
返回不同的字节数:
我编辑的部分:
//
// Dump Cipher Text
//
std::cout << "Cipher Text (" << ciphertext.size() << " bytes)" << std::endl; // returns 16 bytes.
int num = ciphertext.size(); // num returns 16 here
for (int i = 0; i < ciphertext.size(); i++) {
std::cout << "0x" << std::hex << (0xFF & static_cast<byte>(ciphertext[i])) << " ";
}
std::cout << std::endl << std::endl;
std::cout << "Ciphertext size: " << ciphertext.size() << std::endl; // now it's 10 bytes?
std::cout << "num: " << num; // returns 10 bytes?! what the hell...
std::cout << std::endl << std::endl;
所以我碰到了这个,因为我试图打印ASCII字符而不是十六进制字节,它工作,但我就是不明白为什么…
因为这个:
std::cout << "To Text: ";
for (int x = 0; x < ciphertext.size(); x++)
{
std::cout << ciphertext[x];
}
打印所有ASCII字符(而不是十六进制),但是…由于ciphertext.size()
返回10,它不应该打印所有的字符(因为它最初被定义为16而不是10),但是,它确实完美地打印了它们....我真的很困惑。变量如何重新定义自己,即使我放置/复制它在int
,以确保它不会得到改变?
std::hex将表示数字的基数改为16(十六进制)。std::cout << std::hex
之后插入std::cout
的所有数字都以16为进制。
ciphertext.size()
仍然返回16,但是,由于之前发送到输出的std::hex
,它以16为基数显示,它的十六进制表示当然是10
。
试试这个:
std::cout << std::dec << "Ciphertext size: " << ciphertext.size() << std::endl;
再次设置10
作为数字表示的基数,并使ciphertext.size()
返回的值显示为16
加密输出为二进制字节,取值范围为0 ~ 255。ASCII可打印字符的范围是32 ~ 127。也许你现在就能看出问题所在了。
不是所有的字节值都可以用ASCII表示,甚至扩展ASCII或unicode也不行,这就是为什么十六进制和Base64被用于加密输出的原因。
参见ASCII字符值
相关文章:
- C++,在int数组中输入字符串或字符会输出0,而不是ascii或error
- 字符的输入/输出操作
- 如何读取单个字符并在输入两个字符序列时输出? 使用 while 循环和C++
- C++输出奇怪的字符而不是数字 (Windows)
- 如何存储 unicode 字符并将其输出到文件?
- C++中附加的字符*的奇怪输出
- 来自无符号字符缓冲区的虚拟输出
- 将未签名的字符写入输出文件
- 在大小为 10 的 char 数组中输入超过 10 个字符的字符串并输出时,它会显示整个数组而不是前 10 个数组.为什
- 如果我们在其中输入一个整数,则字符会给出整数作为输出,但是当分配给它一个整数时,这不会发生。为什么?
- 字符数组到十六进制字符串的转换 - 意外输出
- 存储和打印字符,但输出不是预期的
- 在函数中连接两个字符,并在 C++ 中返回输出
- 为什么要更改这两个代码的输出"&"字符?
- 输出字符时出现分段错误**
- 如何输出字符**
- C ++中的输出字符数组会产生奇怪的符号
- 输出字符的ASCII值
- 输出字符文字 { 以流C++
- 无法在结构中输出字符