uint8_t *)data; length--; ++byte) { if (*byte) // Byte not zero, write it *encode++ = *byte, ++code; if (!*byte || code == 0xff) // Input is zero or block completed, restart { *codep = code, code = 1, codep = encode; if (!*byte || length) ++encode; } } *codep = code; // Write final code value return (size_t)(encode - buffer); } /** COBS decode data from buffer @param buffer Pointer to encoded input bytes @param length Number of bytes to decode @param data Pointer to decoded output data @return Number of bytes successfully decoded @note Stops decoding if delimiter byte is found */ size_t cobsDecode(const uint8_t *buffer, size_t length, void *data) { assert(buffer && data); const uint8_t *byte = buffer; // Encoded input byte pointer uint8_t *decode = (uint8_t *)data; // Decoded output byte pointer for (uint8_t code = 0xff, block = 0; byte < buffer + length; --block) { if (block) // Decode block byte *decode++ = *byte++; else { if (code != 0xff) // Encoded zero, write it *decode++ = 0; block = code = *byte++; // Next block length if (!code) // Delimiter code found break; } } return (size_t)(decode - (uint8_t *)data); } See also Bit stuffing Serial Line Internet Protocol References External links Python implementation Alternate C implementation Another implementation in C Consistent Overhead Byte Stuffing—Reduced (COBS/R) A patent describing a scheme with a similar result but using a different method Encodings