Can we exchange the contents of a data buffer, which is a fixed-size array, before matching it with its possible data structure?

Scenario: The remote machine (big endian) sends a message to the local computer (small end) via RS422.

The local machine receives the message as a buffer, i.e. dataBuffer, which is an array of 4 16-bit ints. This buffer data will eventually be mapped to data MainTypesomewhere in the program, but this is not our problem. We need a function that changes bytes (changes the essence) using the method swapData().

Question: Considering the fact that each AND MainTypehas exactly 4data members , it is an array of size 4 and each of the data is 16 bits, can we just swap the data in the buffer without reference to the data structure (as shown below)?16 bitsdataBufferMainType

Limitations:

  • dataBuffer must be global in the program,
  • In swapData()need to swap the swap,
  • data will be filled in some other way, such as useData()

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.
    ....
}
+4
source share
1 answer

If the behavior of the remote computer is blocked, you can examine and determine what encoding of bit fields on this platform is, and accordingly transfer the buffer received on the local computer.

, 16- , W, , struct OtherType, , . , , 1 , 0 16- .

- W , W.h 1 . , W . a b c d e f g h1 h0 i2 i1 i0 j3 j2 j1 j0 16- W, , <a b c d e f g h1> <h0 i2 i1 i0 j3 j2 j1 j0> 16 , h0 i2 i1 i0 j3 j2 j1 j0 a b c d e f g h1, dont , . , , j3 j2 j1 j0 i2 i1 i0 h1 h0 g f e d c b a, -, , .

- , , , , -.

+1

Source: https://habr.com/ru/post/1625418/


All Articles