LabWindows/CVI

cancel
Showing results for 
Search instead for 
Did you mean: 

Data types in an union - byte swapping

Hi
 
I´m using CVI 7.0 and I have a problem with an union type definition in a Modbus application.
 
I have defined the following type:
 
typedef union
{
  unsigned char Buffer[20];
  union
    {
      struct
      {
        unsigned char RegAdrHigh;
        unsigned char RegAdrLow;
        unsigned char NumRegHigh;
        unsigned char NumRegLow;
        unsigned char CRCHigh;
        unsigned char CRCLow;
      }Bytes;
     
      struct
      {
        unsigned short RegAdr;
        unsigned short NumReg;
        unsigned short CRC;
      }Read;
       }Func;
  }Frame; 
}*Query_t;
 
 
Serial data are read into the Buffer variable inside the union:
Query->Buffer[i] = ComRdByte (...);
 
If I access the union with the char variables I will receive the right byte values, but if I access the union with the short variables the byte order is swapped.
For example:
Access to char variables:
"Query->Frame.Func.Bytes.RegAdrHigh"    shows 0x00
"Query->Frame.Func.Bytes.RegAdrLow"    shows 0x01
"Query->Frame.Func.Bytes.NumRegHigh" shows 0x00
"Query->Frame.Func.Bytes.NumRegLow"  shows 0x01
"Query->Frame.Func.Bytes.CRCHigh"       shows 0xD5
"Query->Frame.Func.Bytes.CRCLow"        shows 0xCA
 
Access to sort variables:
"Query->Frame.Func.Read.RegAdr"       shows 0x100      -> this should be 0x01
"Query->Frame.Func.Read.NumReg"     shows 0x100      ->  this should be 0x01
"Query->Frame.Func.Read.CRC"           shows 0xCAD5   -> this should be 0xD5CA
 
 
Can anybody tell my why this phenomenon occur? Is this related to little/big endian? 
In the memory display shows that the bytes stored in the right order (0x00, 0x01, 0x00, 0x01, 0xD5, 0xCA).
 
Many thanks in advance for your hints!
Thomas

 
0 Kudos
Message 1 of 2
(3,644 Views)

Every time I used Modbus protocol to communicate with some equipment I had to swap bytes both for integers and for floating point variables. Here the function I use to treat shorts:

short conv_word_to_short (unsigned char * buf)
{
 return ((*(buf + 0)) << 😎 +
   (*(buf + 1));
}



Proud to use LW/CVI from 3.1 on.

My contributions to the Developer Community
________________________________________
If I have helped you, why not giving me a kudos?
0 Kudos
Message 2 of 2
(3,641 Views)