Link to home
Start Free TrialLog in
Avatar of star6868
star6868

asked on

How to replace BYTE buffer with C++, MFC...?

I have a BYTE buffer array (Binary data, may be load from a file)
I want to replace any sub-buffer by other sub-buffer
Like String Replace (with CString for example)

It seems, many samples of replacing string to string. But with Buffer of Byte, I have not found yet!

How to do this work most quickly?

Thanks in advanced!
Avatar of AndyAinscow
AndyAinscow
Flag of Switzerland image

Step into the CString::Replace function and have a look at how the buffer replacement is implemented there.  Make a copy of the code.  Now modify it to suit your requirements - the logic should be the same.
Avatar of isprabu
isprabu

star6868,
You can use one of the popular search alogrithms to accomplish your task. "Boyer-Moore algorithm" is one such :http://www-igm.univ-mlv.fr/~lecroq/string/node14.html#SECTION00140
The above link has complete code sample - which you can port to your needs.

Hope this helps!
memcpy()

use BYTE instead of char in this example
http://www.cplusplus.com/reference/clibrary/cstring/memcpy.html
ASKER CERTIFIED SOLUTION
Avatar of itsmeandnobodyelse
itsmeandnobodyelse
Flag of Germany image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of star6868

ASKER

@ itsmeandnobodyelse:
Exactly, I tried your code, it runs well
I'm not familliar with Standar LIBbrary (STD) of C++, I know that's simple if I use well STDLIB!
Thanks!
>>>> I know that's simple if I use well STDLIB!
CString was able to handle binary strings and substrings same as std::string. But unfortunately there is no CString::Find that takes a CString as argument but only a zero-terminated LPCTSTR, what makes it unapplicable for searching binary byte-sequences (even if you were using CString with non-UNICODE settings).  

So you are right, std::string is indeed the better choice for storing and handling binary data.
   while ((pos2 = buf.find(buffind, pos1)) != std::string::npos)
   {     
          // replace found buffer
          buf    = buf.substr(0, pos2) + bufrepl + buf.substr(pos2+sizfind);
          // next pos is after the replaced string to prevent from infinite loop
          pos1 = pos2+sizreplace;
   }

Open in new window