AndaMan
Junior Member level 3
This bit counting code snippet idea was took from chip design (VHDL) people and implemented in ST to count number of active switch (arrange in 16 bits word) or to detect co-incident switches. It is fast, no looping, complete in single scan cycle. Can modify to support less or more bits.
FUNCTION_BLOCK BIT_CNT
VAR_INPUT
_w: WORD; (* input 16 contacts *)
END_VAR
VAR_OUTPUT
_cnt: INT; (* number of active contacts *)
END_VAR
VAR
END_VAR
_w := (_w AND 16#5555) + (SHR(_w,1 ) AND 16#5555);
_w := (_w AND 16#3333) + (SHR(_w,2 ) AND 16#3333);
_w := (_w AND 16#0F0F) + (SHR(_w,4 ) AND 16#0F0F);
_w := (_w AND 16#00FF) + (SHR(_w,8 ) AND 16#00FF);
_cnt := WORD_TO_INT(_w);
END_FUNCTION_BLOCK
FUNCTION_BLOCK BIT_CNT
VAR_INPUT
_w: WORD; (* input 16 contacts *)
END_VAR
VAR_OUTPUT
_cnt: INT; (* number of active contacts *)
END_VAR
VAR
END_VAR
_w := (_w AND 16#5555) + (SHR(_w,1 ) AND 16#5555);
_w := (_w AND 16#3333) + (SHR(_w,2 ) AND 16#3333);
_w := (_w AND 16#0F0F) + (SHR(_w,4 ) AND 16#0F0F);
_w := (_w AND 16#00FF) + (SHR(_w,8 ) AND 16#00FF);
_cnt := WORD_TO_INT(_w);
END_FUNCTION_BLOCK