(c++)将十六进制字符串写入文件

(C++) Write string of hex to a file

本文关键字:文件 字符串 十六进制 c++      更新时间:2023-10-16

我快疯了。我是一个初学者/中级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.
}