Endianness in encoders
The encoding of values to and from the network needs to take into account the endianness of the host platform.
In the current implementation, one needs to call the SOPC_Helper_EndiannessCfg_Initialize()
function which detects at runtime the endianness of the running platform and sets appropriate function pointers for encoding/decoding integers and floats.
In the case of integers, it would be possible to use another approach. Use a piece of code which is independent of the endianness of the platform and get rid of the function pointers. This would be neater.
In terms of efficiency, if the platform uses the same byte order as the network, this piece of code will be optimised out by the compiler.
An example of such as a piece of code is
#include <stdio.h>
#include <stdint.h>
#include <inttypes.h>
static void
convert_uint32(uint8_t *buf, uint32_t value)
{
#if 1
buf[0] = (uint8_t) ((value >> 0) & 0xFF);
buf[1] = (uint8_t) ((value >> 8) & 0xFF);
buf[2] = (uint8_t) ((value >> 16) & 0xFF);
buf[3] = (uint8_t) ((value >> 24) & 0xFF);
#else
uint8_t *p = (uint8_t *) &value;
buf[0] = p[0];
buf[1] = p[1];
buf[2] = p[2];
buf[3] = p[3];
#endif
}
int main(int argc, char **argv)
{
uint32_t value;
uint8_t buf[sizeof value];
if (1 == argc || 1 != sscanf(argv[1], "%" SCNx32, &value))
{
fprintf(stderr, "usage: %s <int-value-in-hex>\n", argv[0]);
return 1;
}
convert_uint32(buf, value);
printf("%2x %2x %2x %2x\n", buf[0], buf[1], buf[2], buf[3]);
return 0;
}
As soon as option -O1
is passed to GCC, the two alternatives of the #if
compile to the exact same assembly code.