Scenario: A remote machine (big endian) sends a message to a local machine (little endian) over RS422.
The local machine gets the message as a buffer, i.e. dataBuffer
which is an array of 4 16-bit ints. This buffer data eventually be mapped to a MainType
data somewhere in the program but this is not our concern. We need a function that swaps the bytes (change the endianness) using the swapData()
method.
Question: Given the fact that MainType
has exactly 4
data members each 16 bits
AND dataBuffer
is array of size 4 and each data is 16 bits, can we just swap the data in the buffer WITHOUT mapping it to MainType
data structure (as below)?
Constraints:
- The
dataBuffer
needs to be global in the program, - Swapping needs to be taken care of in
swapData()
function, - The
data
will be filled in some other method such asuseData()
Here is the code:
...
typedef unsigned short int USINT16;
typedef struct {
USINT16 a : 1;
USINT16 b : 1;
USINT16 c : 1;
USINT16 d : 1;
USINT16 e : 1;
USINT16 f : 1;
USINT16 g : 1;
USINT16 h : 2;
USINT16 i : 3;
USINT16 j : 4;
} OtherType; // 16 bits
typedef struct {
USINT16 X;
USINT16 Y;
USINT16 Z;
OtherType W;
} MainType;
...
unsigned short dataBuffer[4]; // available in global scope
...
void swapData() {
receiveData(&dataBuffer); // data buffer is filled
int i;
for (i = 0; i < 4; i++) {
dataBuffer[i] = __builtin_bswap16(dataBuffer);
}
// The data is little endian now ?
}
...
void useData() {
MainType data; // map the swapped buffer to data
// use the data etc.
....
}