mrg95
mrg95

Reputation: 2418

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

This is driving me insane. I'm a beginner/intermediate C++er and I need to do something that seems simple. I have a string with A LOT of hex characters in it. They were inputted from a txt file. The string looks like this

07FF3901FF030302FF3f0007FF3901FF030302FF3f00.... etc for a while

How can I easily write these hex values into a .dat file? Everytime I try, it writes it as text, not hex values. I already tried writing a for loop to insert "\x" every byte but it still is written as text.

Any help would be appreciated :)

Note: Obviously, if I can even do this, then I don't know that much about c++ so try not to use things WAY over my head. Or at least explain it a bit. Pweeeez:)

Upvotes: 2

Views: 3072

Answers (1)

Sayalic
Sayalic

Reputation: 7650

You should be clear about the difference of char(ascii) and hex values.

Assume in x.txt:

ascii reads as: "FE"

In binary ,x.txt is "0x4645(0100 0110 0100 0101)".In ascii, 'F'=0x46,'E'=0x45.

Notice everything is computer is stored in binary code.

You want to get x.dat:

the binary code of x.dat is "0xFE(1111 1110)"

So, you should tranfer the ascii text into the proper hex values then write it into the x.dat.

The sample code:

#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.
}

Upvotes: 1

Related Questions