Reputation: 33
i have a hex valued string that is saved in a text file. I want to get it into a c style include format to just copy and paste into my code. i tried using xxd that has a feature to do that but for some reason when i use my file it takes that string (it considers it non hex) and further converts it into hexadecimal.
anyway around this or an easier way to do this in c++. I am not sure. pretty new to c++ and just learning here.
sample of the contents of the file are as follows:
AFAB2591CFB70E77C7C417D8C389507A541D0350752EE9E8C12D76E8674677C166A5ACA65ECFDE7EC90DC8E7D6D621438FEF7DD38B0EDEA3D44BDB9D6E7E1CA0FBA30B507EA70B2A52434F64092EC13BD12F8F1C2BED6EE1ADE7
so getting it like 0xAF, 0xAB etc is what i am looking for.
i also noticed that when i use xxd even if i just put A in the file...its result is 410a. I don't understand that either. is it showing a word rather than just a byte?
Upvotes: 0
Views: 353
Reputation: 9937
You can use any regular expression editor to convert
AFAB2591CFB70...
to 0xAF, 0xAB, 0x25, 0x91, 0xCF, 0xB7, ...
I use MSFT Visual Studio and this is a snap with the RE option of it's "Find-and-Replace" tool. Find any expression consisting of any char in the set [0-9A-Fa-f] followed by another char in the same set; tag the expression; replace it with "0x" + tagged expression + ", ". (Don't match whole words.)
If you're using a different GUI dev tool, you should be easily able to find a command line sed (Linux or Cygwin) or something similar.
Upvotes: 1
Reputation: 25063
Looks like homework, but what the heck. Compile this into filter.exe and then:
filter < inputfile.txt > outputfile.cpp
#include <iostream>
using namespace std;
int main(int argc, char* argv[])
{
char a, b;
while (!cin.eof()) {
cin >> a >> b;
cout << "0x" << a << b << ", ";
}
return 0;
}
Upvotes: 0
Reputation: 5508
ok well first dude get the code to find the string like so
#include <iostream>
#include <conio.h>
#include <fstream>
#include <iostream>
using namespace std;
class FindHex {
string x, y;
public:
void set_values (string,string);
string found () {return (x,y);}
};
void FindHex::set_values ( string a, string b) {
cout<<a<<" "<<b;
x = a;
y = b;
}
FindHex hex;
int main () {
char Name[10];
char LName[10];
ifstream inf("Data.txt");
while(!inf.getline(Name, 30, '0x').eof())
{
inf.getline(LName, sizeof(LName));
hex.set_values (Name,LName);
hex.found();
cin.ignore();
}
}
Upvotes: 0
Reputation: 44782
string s = ...; // Read the string into this
stringstream buffer;
for (size_t i = 0; i < s.length(); i += 2) {
char tmp[3] = { s[i], s[i + 1], 0 };
buffer << (char)strtol(tmp, NULL, 16);
}
const string final = buffer.str();
There you go!
Upvotes: 0