用c++程序以不同的基数输出不可打印字符

Output non-printable characters in different bases with a C++ program?

本文关键字:输出 字符 打印 c++ 程序      更新时间:2023-10-16

我认为这是一个简单的问题。我正在摆弄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字符值