You could probably set up some ADD logic and look at the bit level of the Dint. Set the result to zero at the beginning of the scan. If Dint.0 = 1 then Add 1 to result.If Dint.1 = 1 then Add 1 to result and so on. At the end result in your example would be 3.
You could also do it with some loop logic and indirect addressing for the bit but that gets a little more complicated.
You can search the forum for "bit hacks" and find a few clever methods but none of them will execute faster, or be faster for you to program, than a brute force subroutine.
CLR NUMBITS
SOR XIC MYDINT.0 ADD 1 NUMBITS NUMBITS EOR
SOR XIC MYDINT.1 ADD 1 NUMBITS NUMBITS EOR
SOR XIC MYDINT.2 ADD 1 NUMBITS NUMBITS EOR
.
.
.
SOR XIC MYDINT.31 ADD 1 NUMBITS NUMBITS EOR
Then I guess you have a lot of typing
The above examples don't care how many words you have. They are basically looking at at boolean. Either on or off.
I am not familiar with controllogix.
This is one simple code written in C
long count_bits(long n) {
unsigned int c; // c accumulates the total bits set in v
for (c = 0; n; c++)
n &= n - 1; // clear the least significant bit set
return c;
}
I hope you are able to translate it to your language
You can program a FOR-NEXT loop but it will execute slower than a brute force subroutine, and if you aren't an experienced programmer it will take you more time to program the loop. In the amount of time spent on this thread you could have completed the task and moved on.
If you want to enter the rungs really fast then open a text editor and paste the mnemonics "SOR XIC MYDINT.0 ADD 1 NUMBITS NUMBITS EOR " for 32 rungs without any line returns. In the text editor increment the bit number MYDINT.# for each of the bits. Then in RSLogix open the mnemonic editor by double clicking on the rung number for a blank rung. The mnemonic editor line will open at the top of your screen. Paste in the entire long string from the text editor and press enter. RSLogix will paste in 32 rungs.
Have you searched the forum on "bit hacks" yet? We've discussed bit counting schemes ad-naseum here.
Then I guess you have a lot of typing
The above examples don't care how many words you have. They are basically looking at at boolean. Either on or off.
Make sure you stick all that in a subroutine so that you don't have to slog you way through it just to find some other piece of code in the future. In the subroutine once its debugged you can forget about it and never look at it again.