Welcome to our new forum
All users of the legacy CODESYS Forums, please create a new account at account.codesys.com. But make sure to use the same E-Mail address as in the old Forum. Then your posts will be matched. Close

CODESYS bit count in a word

mlepine
2021-01-09
2021-01-10
  • mlepine - 2021-01-09

    Hi Every body,

    I'm pretty new here and i'm trying to put in place a function that will count the number of bit that are SET in a word or a Dword.

    Could some body help me ?

    Thk in advance

     
  • wollvieh

    wollvieh - 2021-01-09

    Do yo know the Bitoperator, for examaple Byte.0, Byte.1, or Word.0... Word.15 ? You could build a loop and, depending on the state of the Bitstate, count the state of the Bits.

     
  • hermsen

    hermsen - 2021-01-09

    The following is pseudocode, don't take it too literal allthough I guess it will probably run ;-)

    (* DECLARATION *)
    VAR
        size, i : INT;
        Bitcount : INT := 0;
        CurBoolVal : BOOL;
        TheWordIWantToCheck : WORD;
    END_VAR
    
    (* CODE *)
    size := SIZE_OF(TheWordIWantToCheck); (* dependends on processor memory width but I assume 16 for now *)
    FOR i := 0 TO size - 1 DO (* eg. count bit 0 to 15 *)
        CurBoolVal := TheWordIWantToCheck.i;  (* Helper to cast Bit i to Bool *)
        BitCount := BitCount + BOOL_TO_INT(CurBoolVal); (* cast Bit i to Bool *)
    END_FOR;
    
    (* after this loop has ended, BitCount will contain the counted bits that are TRUE in the word *)
    
     

    Last edit: hermsen 2021-01-09
  • wollvieh

    wollvieh - 2021-01-10

    How about that ...

     

Log in to post a comment.