简体   繁体   English

将CString写入.bin文件

[英]writing a CString into a .bin file

I have a CString with 'HEX' values, which looks something like this: "0030303100314a" 我有一个带有'HEX'值的CString,看起来像这样:“0030303100314a”

Now I want to store this into a bin file, so that if I open it with a hex-editor, the data us displayed is displayed like in the string: 00 30 30 30 31 00 31 4a 现在我想将它存储到bin文件中,这样如果我用十六进制编辑器打开它,我们显示的数据就会显示在字符串中:00 30 30 30 31 00 31 4a

I fail to prepare the data right. 我没有正确准备数据。 It gets always saved in standard ASCII even though I use the "wb" mode. 即使我使用“wb”模式,它也始终以标准ASCII保存。

Thanks in advance 提前致谢

OK your misunderstanding is that "wb" means that all output happens in 'binary'. 好吧你的误解是“wb”意味着所有输出都以'二进制'形式出现。 That's not what it does at all. 这根本不是什么。 There are binary output operations, and you should open the file in binary mode to use them, but you still have to use binary output operations. 有二进制输出操作,您应该以二进制模式打开文件以使用它们,但您仍然必须使用二进制输出操作。 This also means you have to do the work to convert your hex characters to integer values. 这也意味着您必须完成将十六进制字符转换为整数值的工作。

Here's how I might do your task 这是我如何完成你的任务

for (int i = 0; i + 1 < str.GetLength(); i += 2)
{
    int hex_value = 16*to_hex(str[i]) + to_hex(str[i+1]); // convert hex value
    fputc(hex_value, file);
}

static int to_hex(TCHAR ch)
{
    return ch >= '0' && ch <= '9' ? ch - '0' : ch - ('A' - 10);
}

The program od will take a file and convert it to various representations. 程序od将获取一个文件并将其转换为各种表示形式。 For example, if you say od -x myfile.bin , the contents of myfile.bin will be printed as hexadecimal bytes, just like what you're looking for. 例如,如果你说od -x myfile.binod -x myfile.bin的内容将打印为十六进制字节,就像你正在寻找的那样。 You could make C++ do this too, but maybe it's easier to just post-process your data to look the way you want. 您可以让C ++也这样做,但也许更容易只是按照您想要的方式对数据进行后处理。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM