c++ - 如何将 ASCII 字符的十六进制值写入文本文件?

标签 c++ ascii hex ofstream

这是我目前所拥有的:

void WriteHexToFile( std::ofstream &stream, void *ptr, int buflen, char *prefix )
{
    unsigned char *buf = (unsigned char*)ptr;

    for( int i = 0; i < buflen; ++i ) {
        if( i % 16 == 0 ) {
            stream << prefix;
        }

        stream << buf[i] << ' ';
    }
}

我尝试过使用 stream.hex、stream.setf(std::ios::hex),以及在 Google 上搜索了一下。我也试过:

stream << stream.hex << (int)buf[i] << ' ';

但这似乎也不起作用。

这是它当前产生的一些输出的示例:

Í Í Í Í Í Í Í Í Í Í Í Í Í Í Í Í 
Í Í Í Í Í Í Í Í Í Í Í Í Í Í Í Í 
Í Í Í Í Í Í Í Í Í Í Í Í Í Í Í Í 
Í Í Í Í Í Í Í Í Í Í Í Í Í Í Í Í 
Í Í Í Í Í Í Í Í Í Í Í Í Í Í Í Í 
Í Í Í Í Í Í Í Í Í Í Í Í Í Í Í Í 

我希望输出如下所示:

FF EE DD CC BB AA 99 88 77 66 55 44 33 22 11 00
FF EE DD CC BB AA 99 88 77 66 55 44 33 22 11 00
FF EE DD CC BB AA 99 88 77 66 55 44 33 22 11 00
FF EE DD CC BB AA 99 88 77 66 55 44 33 22 11 00
FF EE DD CC BB AA 99 88 77 66 55 44 33 22 11 00
FF EE DD CC BB AA 99 88 77 66 55 44 33 22 11 00

最佳答案

#include <iostream>
using namespace std;
int main() {
    char c = 123;
    cout << hex << int(c) << endl;
}

编辑:零填充:

#include <iostream>
#include <iomanip>
using namespace std;
int main() {
    char c = 13;
    cout << hex << setw(2) << setfill('0') << int(c) << endl;
}

关于c++ - 如何将 ASCII 字符的十六进制值写入文本文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/623784/

相关文章:

c++ - 如何在 C/C++ 中创建 JNIEnv 模拟

c++ - 为插入排序获得有趣的输出

java - 将字符附加到文件

elasticsearch - 在ElasticSearch中使用 token 化器“asciifolding”的“pattern”

java - 使用 for 循环和 if 语句以行/表格式打印字符 (Ascii)?

c# - 在 C# 中从十六进制到字节的最轻量级转换?

mysql - 如何在 mysql 槽查询中插入 BLOB

c++ - vector 分配问题

c++ - 在 Vista 上调用 RPC 调用时为 "operation is not supported"

python - 将 ASCII 码序列作为整数转换为字符串