When packetized data is sent over any serial medium, some protocol is required to demarcate packet boundaries. This is done by using a framing marker, a special bit-sequence or character value that indicates where the boundaries between packets fall. Data stuffing is the process that transforms the packet data before transmission to eliminate all occurrences of the framing marker, so that when the receiver detects a marker, it can be certain that the marker indicates a boundary between packets.
COBS transforms an arbitrary string of bytes in the range [0,255] into bytes in the range [1,255]. Having eliminated all zero bytes from the data, a zero byte can now be used to unambiguously mark the end of the transformed data. This is done by appending a zero byte to the transformed data, thus forming a packet consisting of the COBS-encoded data (the payload) to unambiguously mark the end of the packet.
(Any other byte value may be reserved as the packet delimiter, but using zero simplifies the description.)
There are two equivalent ways to describe the COBS encoding process:
These examples show how various data sequences would be encoded by the COBS algorithm. In the examples, all bytes are expressed as hexadecimal values, and encoded data is shown with text formatting to illustrate various features:
Below is a diagram using example 4 from above table, to illustrate how each modified data byte is located, and how it is identified as a data byte or an end of frame byte.
Examples 7 through 10 show how the overhead varies depending on the data being encoded for packet lengths of 255 or more.
The following code implements a COBS encoder and decoder in the C programming language, processing data byte by byte.
A possibly faster encoder and decoder using standard library functions is presented below.
Cheshire, Stuart; Baker, Mary (April 1999). "Consistent Overhead Byte Stuffing" (PDF). IEEE/ACM Transactions on Networking. 7 (2): 159–172. CiteSeerX 10.1.1.108.3143. doi:10.1109/90.769765. S2CID 47267776. Retrieved November 30, 2015. /wiki/Stuart_Cheshire ↩
Cheshire, Stuart; Baker, Mary (17 November 1997). Consistent Overhead Byte Stuffing (PDF). ACM SIGCOMM '97. Cannes. Retrieved November 23, 2010. /wiki/Stuart_Cheshire ↩
Carlson, James; Cheshire, Stuart; Baker, Mary (November 1997). PPP Consistent Overhead Byte Stuffing (COBS). I-D draft-ietf-pppext-cobs-00.txt. /wiki/Stuart_Cheshire ↩