How do I find Byte patterns in a byte array, and represent them if it's available in checkedlistbox in C#?
I am trying to make software to search for byte patterns, I have many bin files and many patterns to search. If the pattern exists on the file. it will represent it on CheckedListBox with a specific name . and if the checked box is unchecked for a particular one , it will replace the pattern with 0000000000 on the saved file. For example, I have this pattern to search (note that I have more than 100 patterns to search): {"2004940101000078", "3004940101000078", "3E04940101000028", .... ,.... }
- Open the bin file by OpenFileDialog
- Covert the file to byteArray
- Search for the patterns
- put the result on checkedlist Box (2004940101000078 = P0420) (3004940101000078 = P0430) (3E04940101000028 =P043E),note P0420 is the name that i want to put on the checkedbox:
DTC Description Checkedbox P0420 Catalyst System Efficiency Below Threshold Bank1 Checkedbox P0430 Catalyst System Efficiency Below Threshold Bank2 Checkedbox P043E EvaporativeEmissionSystemLeakDetectionReferenceOrificeLowFlow - If I want to delete the code P0420 , uncheckedbox P0420
replace 2004940101000078 with 0000000000000000and save it to a new bin file
I tried with this code to search for the patterns, but its give the offset position of the pattern only. please this code-only example and part of my codes. if you have a solution or other code or way. please help, I am new in C#
string hex2 = BitConverter.ToString(byteArray).Replace("-", string.Empty);
string[] patterns = {"2004940101000078", "3004940101000078", "3E04940101000028" };
foreach (string p in patterns)
{
int i = 0;
int indice = 0;
// teminate loop when no more occurrence is found;
while (indice != -1)
{
// index if the pattern is found AFTER i position, -1 if not
indice = hex2.IndexOf(p, i);
i = indice + 0; // skip the pattern occurrence itself
int indexxx = (i / 2);
//Transform the index into hexadecimal
string outputHex = int.Parse(indexxx.ToString()).ToString("X");
//Output the index as an hexadecimal offset address
MessageBox.Show("0x" + outputHex);
break;
}
}
Naimish MakwanaPosted Feb 8, 2023, 5:10 AM
Hello Malik,
You can try below solution.
1. Open the bin file using OpenFileDialog and read the contents into a byte[] array.
2. Create a dictionary to map the byte patterns to their corresponding names, e.g. "2004940101000078" -> "P0420", etc.
3. Loop through the dictionary and use the IndexOf method to search for each pattern in the byte[] array. If a pattern is found, add the corresponding name to the CheckedListBox control.
4. When the user unchecks a name in the CheckedListBox, search for the corresponding byte pattern in the byte[] array and replace it with 0000000000.
5. Save the modified byte[] array to a new file using a FileStream.
Thanks
Naimish Makwana