这让我发疯。我是初学者/中级C++ er,我需要做一些看起来很简单的事情。我有一个带有很多十六进制字符的字符串。它们是从txt文件输入的。字符串看起来像这样
07FF3901FF030302FF3f0007FF3901FF030302FF3f00.... etc for a while
我如何轻松地将这些十六进制值写入.dat文件?每次尝试时,它都会将其写为文本,而不是十六进制值。我已经尝试编写一个for循环以在每个字节中插入“\ x”,但仍将其写为文本。
任何帮助,将不胜感激 :)
注意:显然,如果我什至可以做到这一点,那么我对c++的了解也不多,因此请尽量不要过度使用。或至少解释一下。 Pweeeez :)
最佳答案
您应该清楚char(ascii)和hex值的区别。
假设在x.txt中:
ascii读为:“FE”
在二进制文件中,x.txt是“0x4645(0100 0110 0100 0101)”。在ascii中,'F'= 0x46,'E'= 0x45。
请注意,一切都是计算机以二进制代码存储。
您要获取x.dat:
x.dat的二进制代码是“0xFE(1111 1110)”
因此,您应该将ascii文本转换为适当的十六进制值,然后将其写入x.dat。
示例代码:
#include<iostream>
#include<cstdio>
using namespace std;
char s[]="FE";
char r;
int cal(char c)// cal the coresponding value in hex of ascii char c
{
if (c<='9'&&c>='0') return c-'0';
if (c<='f'&&c>='a') return c-'a'+10;
if (c<='F'&&c>='A') return c-'A'+10;
}
void print2(char c)//print the binary code of char c
{
for(int i=7;i>=0;i--)
if ((1<<i)&c) cout << 1;
else cout << 0;
}
int main()
{
freopen("x.dat","w",stdout);// every thing you output to stdout will be outout to x.dat.
r=cal(s[0])*16+cal(s[1]);
//print2(r);the binary code of r is "1111 1110"
cout << r;//Then you can open the x.dat with any hex editor, you can see it is "0xFE" in binary
freopen("CON","w",stdout); // back to normal
cout << 1;// you can see '1' in the stdout.
}
关于c++ - (C++)将十六进制字符串写入文件,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16454641/