The following technique illustrates one way to encode a frame buffer with an Ethernet header followed by an Atheros message header. We first declare the frame buffer then a length variable to keep track of how many bytes have actually been encoded. At any time, the value 'buffer + length' is the address of the next buffer position to encode and the expression 'sizeof (buffer) - length' is the number of un-encoded bytes remaining in the buffer. Each call to an encoding function will increment the length for the next operation. This technique minimizes the number of intermmediate application variables and makes maximum use of compiler generated constants.
Example 3.9. Frame Encoding by Offset
uint8_t buffer [ETHER_MAX_LEN]; size_t length = 0; uint8_t OSA [ETHER_ADDR_LEN] = { 0x00, 0xB0, 0x52, 0x00, 0xD4, 0x32 }; uint8_t ODA [ETHER_ADDR_LEN] = { 0x00, 0xB0, 0x52, 0x00, 0x66, 0xF7 }; uint16_t MMTYPE = 0xA050; length += EncodeEthernetHeader (buffer + length, sizeof (buffer) - length, uint8_t OSA, uint8_t ODA); length += EncodeAtherosHeader (buffer + length, sizeof (buffer) - length, unit16_t MMTYPE); if (length < sizeof (MME)) { error (...); }
For those who prefer to use pointers, the following technique accomplishes the same thing because. At any given time, the value bp - buffer is the encoded length.
Example 3.10. Frame Encoding by Address
uint8_t buffer [ETHER_MAX_LEN]; uint8_t bp = buffer; bp += EncodeEthernetHeader (bp, buffer + sizeof (buffer) - bp, uint8_t OSA, uint8_t ODA); bp += EncodeAtherosHeader (bp, buffer + sizeof (buffer) - bp, unit16_t MMTYPE); if (bp < (buffer + sizeof (MME))) { error (...); }