How to read, search and change file by bytes?

5

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

For example: in the file it will look like this: 6261725610

I'll look for this:

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

and wanted to return this:

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

Enjoying, how do I subtract the last byte?

for example this:

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

Turn this over:

byte[] findBytes = { 0x62, 0x61, 0x72, 0x56, 0x8 };
    
asked by anonymous 03.07.2015 / 17:03

1 answer

3

Try using this library I've developed - Sequences -, makes handling collections much easier. It has an API identical to the 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 by the substring).

  • AsSequence converts byte[] to ISequence<byte>
  • IndexOfSlice performs an efficient search by substring using the algorithm KMP
  • Skip increments the elements that appear before the sub-sequence and returns the remaining elements.

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 to the end of the sequence.

Links

03.07.2015 / 20:20