How to read, search and change file by bytes?

Asked

Viewed 104 times

5

Does anyone know how to find more bytes after I found the byte sequence of my variable?

for example: in the file will look like this: 6261725610

I’ll look for that:

byte[] findBytes = { 0x62, 0x61, 0x72 };

and wanted to return this:

byte[] resultado = { 0x62, 0x61, 0x72, 0x56, 0x10 };

Taking advantage, how do I subtract the last byte?

for example this:

byte[] findBytes = { 0x62, 0x61, 0x72, 0x56, 0x10 };

had seen this:

byte[] findBytes = { 0x62, 0x61, 0x72, 0x56, 0x8 };
  • It’s java that Pedro?

  • 1

    sorry I forgot to specify...I’m doing in C#

  • 1

    This link might help: http://stackoverflow.com/questions/28224043/c-sharp-find-offset-of-byte-pattern-check-specific-byte-change-byte-export-pa

1 answer

3

Try using this library I developed - Sequences -, makes collection handling much easier. It has an API identical to Scala collections.

var bytes = new byte[] {0x01, 0x02, 0x03, 0x62, 0x61, 0x72, 0x56, 0x10}.AsSequence();
var find = new byte[] {0x62, 0x61, 0x72};


var index = bytes.IndexOfSlice(find);
var remaining = bytes.Skip(index);     //retorna 0x62, 0x61, 0x72, 0x56, 0x10

(I added a few bytes at the beginning of the array to better demonstrate the search for the sub-sequence).

  • AsSequence converts the byte[] in a ISequence<byte>
  • IndexOfSlice does an efficient search by sub-sequence using the algorithm KMP
  • Skip Release the elements that appear before the sub-sequence and return the remaining ones.

To replace the last element:

var replaced = remaining.Init.Append(0x8);   // retorna 0x62, 0x61, 0x72, 0x56, 0x8
  • Init returns the sequence without the last element
  • Append joins an element at the end of the sequence.

Links

  • Very cool this library! Sorry I’m a beginner and I have another question. I need to read bytes and pick up a variable byte size, for example: I read: var bytes = new byte[] {0x01, 0x02, 0x03, 0x62, 0x61, 0x72, 0x56, 0x10}.AsSequence(); searches: var find = new byte[] {0x02}; when it finds 0x02 it must read the next byte (0x03) and assume that it must read 3 more bytes(could be 0x62 or any other), i.e., from the index it finds, it will read one more size than the next byte indicated. knows how to do this?

  • @Pedrohenrique I’m not sure I understand the problem... Want to find a sequence, read the byte that comes after the sequence, convert that byte to an integer n, and read the next n bytes?

  • Exactly :D is for a specific application

  • @Pedrohenrique Try this: https://dotnetfiddle.net/OysZeF

Browser other questions tagged

You are not signed in. Login or sign up in order to post.