HiveBrain v1.2.0
Get Started
← Back to all entries
patterncMinor

Escape some char in a byte array

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
arraycharbytesomeescape

Problem

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

Solution

Hard coding 32 as the size of the destination array regardless of the size if the source array is not so good, as it might not be big enough. Better approaches would be:

  • Make the destination twice as big as the input: that way it will always be big enough to contain the escape zeros. The drawback is that most often it will be too big.



  • Count the number of zeros first, and the allocate the exact size that you need. The drawback is that the counting step is an extra \$O(N)\$ operation. On the other hand, if the counting step find no zeros, then you can skip the copying step. If most input will not contain zeros, then this approach should work pretty well.

Context

StackExchange Code Review Q#92711, answer score: 4

Revisions (0)

No revisions yet.