I am trying to construct a binary message packet. It needs to escape binary value 0 by appending extra 0 in front of it:
//Before escape
data[] = { 1, 2, 3, 4, 5, 0, 6, 7, 8, 9 }
//After escape - value 0 is appended after 0
data[] = { 1, 2, 3, 4, 5, 0, 0, 6, 7, 8, 9 }
My source code:
uint8_t escape_data[32];
uint8_t escape_index = 0;
uint8_t data[] = { 1, 2, 3, 4, 5, 0, 6, 7, 8, 9 };
for (int i = 0; i < sizeof(data); i++)
{
escape_data[escape_index++] = data[i];
if (data[i] == 0) {
escape_data[escape_index++] = 0;
}
}
Is there any elegant way to solve this problem?
P.S the code above is designed to be simple to read, I ignore those array sizing for simplicity and hard coding them, I want to know a good algorithm or a good way to write to solve this problem with the least variable and memory footprint
- Searching for 0
- Appending byte in between array