0

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 some_value'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.

FrozenHeart
  • 19,844
  • 33
  • 126
  • 242

2 Answers2

2

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));
pe_file_content.find(needle);

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.

Miles Budnek
  • 28,216
  • 2
  • 35
  • 52
  • Is it safe to use `reinterpret_cast` like this? – FrozenHeart Nov 02 '16 at 11:39
  • 1
    This is exactly the case that `reinterpret_cast` exists for. The strict aliasing rules explicitly make an exception for referring to any object via a `char*`. – Miles Budnek Nov 02 '16 at 11:46
  • 1
    In case you only use `DWORD` (4 byte values) you can also do the conversion manually: `std::string some_value_str = {{ (char)((some_value & 0xFF000000) >> 24), (char)((some_value & 0x00FF0000) >> 16), (char)((some_value & 0x0000FF00) >> 8), (char)((some_value & 0x000000FF) >> 0) }};` – Simon Kraemer Nov 02 '16 at 11:47
0

I guess you could use the same approach here to convert the DWORD to a stringstream and the use the string::find function to find the position of the number.

Community
  • 1
  • 1
Isaak
  • 66
  • 2
  • You mean like this? `std::ostringstream oss; oss << some_value; pe_file_content.find(oss.str());` It won't work as expected – FrozenHeart Nov 02 '16 at 11:28