Bit Adding code

I have been looking for a simple way to add the number of active bits within a word (or byte).

Example of what I need:

00000000 = 0
00100000 = 1
00001000 = 1
00110000 = 2
00101010 = 3
11001100 = 4
11111111 = 8

The easiest way I've worked out uses a large amount of Word Ands and bit shifting.

Example, word A is the test word. B is a holding word. C is the sum.

B = A WAND 0001
C = C+B
Shift left A by 1 bit
Repeat

This will be for an S7.

Thanks in advance.

Doug
 
It's essentially the same thing, but saves mucking about with WANDs, just use SRW (Shift Right Word) and test for positive afterwards. Actually more sensible would be to test for negative or zero (JMZ) to jump over your addition step.
 
Doug

Try FC99 from the STEP7 Standard Library / TI-S7 Converting Functions. It's called BITSUM, and it takes a double word as input and returns the numbers of bits set in that address as the output.

I've had a look inside the FC and it seems to loop around, shifting the DWORD to the right once each loop, and incrementing the total if the LSB is '1'. You could reduce this to a word or byte-sized loop if need be, or else write your own based on this description.

Regards

Ken.
 

Similar Topics

How to use 32 bit variables in SLC5/03? I need to count more then 40000 counts (m3 of water). Thanks!
14
Replies
3,947
Views
I just tried to update a L61-v20 program to an L81-v34 and I found that addressing a REAL to the bit level is no longer allowed? Can any one...
9
Replies
119
Views
I’d like to hear from others about their experience with the GE MDS Orbit ECRL9, particularly compared with the older MDS 9710. Of the 18 GE MDS...
0
Replies
90
Views
Hello. I am currently working on recreating a FactoryTalk Optix project as a FactoryTalk View SE project (customer request). The PLC code should...
0
Replies
157
Views
I have a Kinetix 350 servo drive that has the Config Update In Process bit always set high. Both the servo drive and the motor has been changed...
1
Replies
258
Views
Top