(c++)将十六进制字符串写入文件
(C++) Write string of hex to a file
我快疯了。我是一个初学者/中级c++ er,我需要做一些看似简单的事情。我有一个字符串,其中有很多十六进制字符。它们是从一个文本文件输入的。字符串看起来像这样
07FF3901FF030302FF3f0007FF3901FF030302FF3f00.... etc for a while
我怎么能很容易地把这些十六进制值写入一个。dat文件?每次我尝试,它将其写入文本,而不是十六进制值。我已经试过写一个for循环来插入"x"每个字节,但它仍然被写为文本。
任何帮助都将是感激的:)
注意:很明显,如果我能做到这一点,那么我就不太了解c++,所以尽量不要使用超出我理解范围的东西。或者至少解释一下。Pweeeez:)
您应该清楚char(ascii)和十六进制值的区别。
假设在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.d 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/C++文件中读取C++原始字符串文字的内容
- 如何打开并写入一个名称取自C++中字符串的文件
- 如何从二进制文件中读取字符串
- 如何在 c++ 中使用 getline 从文件中读取字符串?
- 将字符串与文件上的数据进行比较
- 用户输入字符串的文件附加问题..C++
- 如何从文件中读取两个字符串和数字数组,并将它们存储在对象向量中
- 如何使字符串出现在编译的二进制可执行文件的开头?
- 使用文件内容作为硬编码字符串
- 将文件复制到自定义位置,存在字符串转换问题
- 在 c++ 中连接字符串和整数,以便在 C++ 11 不支持计算机的情况下读取多个文件
- 声明要在 qml 和 cpp 文件中使用的全局字符串
- C 通过char读取文件字符串的文件char;崩溃
- 我不明白如何将 toupper 和 isalpha 与.txt文件字符串输入一起使用
- 在 CPP 文件中使用 make 文件字符串变量
- 编译 PyGAMMA Mac Lion:g++ 找不到标准的 C++ 头文件(字符串/iostream..)
- 如何在c++中使用文件字符串作为命令
- 使用 TinyXML 解析 XML 文件字符串
- 递归下降解析器帮助(不读取文本文件字符串)