Bit-packing in unions of custom structures

pekkallio
2020-03-19
2020-03-30
  • pekkallio

    pekkallio - 2020-03-19

    Hi!

    We need to use custom structures of BITS (not BOOLs) in our projects. For example:

    TYPE ST_3bit :
    STRUCT
        x1: BIT;
        x2: BIT;
        x3: BIT;
    END_STRUCT
    END_TYPE
    

    ...and ST_7bit in the same way. This is mandatory due to requirements of certain devices.

    I combine 3bit and 7bit with a further structure:

    TYPE ST_3bit :
    STRUCT
        x1: BIT;
        x2: BIT;
        x3: BIT;
    END_STRUCT
    END_TYPE
    

    Then, I do a union of the combined structure with WORD.

    TYPE U_Test :
    UNION
        st3_7: ST_3bit_7bit;
        wTest: WORD;
    END_UNION
    END_TYPE
    

    This doesn't work as I would expect. st3bit is copied to WORD correctly but st7bit is byte-aligned to the higher byte of the WORD.

    Example: uUnionTest.st3_7.st3bit.x1 TRUE --> wTest is 256.

    Is there any way I could pack the bits and omit the byte-alignment?

     
  • dFx

    dFx - 2020-03-23

    Please provide ST_3bit_7bit code (copy/paste issue). Providing the expected bit partern over a word would also help.

     

    Last edit: dFx 2020-03-23
  • pekkallio

    pekkallio - 2020-03-23

    Hi,
    here's ST_3bit_7bit:

    TYPE ST_3bit_7bit :
    STRUCT
        st3bit: ST_3bit;
        st7bit: ST_7bit;
    END_STRUCT
    END_TYPE
    

    In pic1 the result is as expected.

    In pic2 I would expect value 15.

     

    Last edit: pekkallio 2020-03-23
  • Lo5tNet - 2020-03-24

    I believe your issue is that the structure size is still a byte. I'm not sure if there is a better way but you might want to look into doing something like this (Instead of a union):

    wTest := SHL((st7bit AND 2#01111111), 3) + (st3bit AND 2#00000111);
    
     

    Last edit: Lo5tNet 2020-03-24
    • pekkallio

      pekkallio - 2020-03-30

      Yes, I'm aware of the problem (see my first message). I would like to avoid using functions here, hence I was asking if there is any way to overcome this byte alignment.

       

Log in to post a comment.