这是我目前所拥有的:
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/