CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2
  1. #1
    Join Date
    Jul 2009

    C++ CLR - How to search hex in a binary file


    I'm trying to search a binary file for some hex values and then replace them, using C++ CLR. Reading and writing the file works, but I just haven't found a way to search and replace successfully. Here is the relevant code I've created:

    array<Byte>^ fileContents = File::ReadAllBytes(item);

    Object^ search = '\x6E' + '\x73' + '\x61' + '\x76' + '\x00' + '\x00' + '\x00' + '\x01';
    int index = Array::BinarySearch(search, fileContents);//I don't have a clue on how to get this to work

    String^ filename = L"aaaa";

    File::WriteAllBytes(filename, fileContents);

  2. #2
    Join Date
    Jul 2002

    Re: C++ CLR - How to search hex in a binary file

    There is no Array function which makes what you need. Array::BinarySearch searches for single array element in sorted array. Array::IndexOf searches for single element in any array.
    You need to implement this functionality in the code. Pseudo-code is:

    Find index of search[0] in fileContents, using IndexOf function.
    If not found - end.
    Compare fileContents[index+1]...fileContents[index+n] with search[1]...search[n]. If all equal, subsequence is found.
    Continue search from current index for next subsequence, using IndexOf.

    Define "search" variable as Byte array, and use Generic Array methods:
    Array.IndexOf Generic Method (T[], T)
    Array.IndexOf Generic Method (T[], T, Int32)

    There are lot optimizations which can be done here, but at least this is something that works. If you are interesting in optimizations, look for different substring or subsequence search algorithms.
    Last edited by Alex F; July 29th, 2009 at 09:23 AM.

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts

Windows Mobile Development Center

Click Here to Expand Forum to Full Width

On-Demand Webinars (sponsored)

We have made updates to our Privacy Policy to reflect the implementation of the General Data Protection Regulation.