FrozenHeart FrozenHeart - 9 months ago 50
C++ Question

How to find an integer inside a string representing a binary file

How can I find an integer inside a string representing a binary file?

For example,

const std::string pe_file_path(argv[1]);
std::ifstream pe_file(pe_file_path, std::ios_base::binary);
const std::string pe_file_content((std::istreambuf_iterator<char>(pe_file)), std::istreambuf_iterator<char>());
DWORD some_value = 0x243e0c10;
// pe_file_content.find(???);

I need to know
's position inside the string.

How can I do it?

Now I'm using the following solution

std::ostringstream some_value_sstr;
some_value_sstr << std::hex << some_value;

std::ostringstream tmp;
for (std::size_t i = 0; i < 4; ++i)
tmp << (char)std::stoi(some_value_sstr.str().substr(i * 2, 2), 0, 16);
std::cout << std::hex << pe_file_content.find(tmp.str()) << std::endl;

but I guess there can be more elegant solution to this problem.

Answer Source

If pe_file_content contains the four bytes 0x24, 0x3E, 0x0C, and 0x10, and not the eight bytes representing them as characters, then you need to convert your DWORD value to a string containing those same bytes, and then you can just search for that:

std::string needle(reinterpret_cast<const char*>(&some_value), sizeof(some_value));

Be careful with byte order. If the integer in your file doesn't have the same endieness as your machine, you'll need to reverse the byte order of some_value before searching.