Page 1 of 1

How do I sum 4 bits to variable

Posted: Fri Nov 09, 2012 6:26 pm
by markus747
I am using tone decoder chip and need sum of D1-D4
I know it should be something like D1+(D2*2)+(D3*4)+(D4*8)
I need to store this to variable to see 1 of 16 decoded outputs
I am new to C programming and don't know sytax

Re: How do I sum 4 bits to variable

Posted: Fri Nov 09, 2012 6:33 pm
by Benj
Hello,

That looks fine to me as long as your values are all 1 to begin with. You can also use shifts which should be a less processor intensive then a multiply.

Data = (D1 + (D2<<1) + (D3 << 2) + (D4 << 3));

You could also use a Logical OR rather then a addition but I don't really think this matters too much.

Data = (D1 | (D2<<1) | (D3 << 2) | (D4 << 3));

If the data maybe isn't 1 then you could maybe do this.

Data = 0;
if (D1)
Data |= 1;
if (D2)
Data |= 1 << 1;
if (D3)
Data |= 1 << 2;

Re: How do I sum 4 bits to variable

Posted: Fri Nov 09, 2012 7:24 pm
by markus747
Still don't get it.
Please look at what I have.
it still doesn't seem to see sum of b.0 b.1 b.2 d.7

Re: How do I sum 4 bits to variable

Posted: Fri Nov 09, 2012 7:32 pm
by markus747
This one is even better.

Re: How do I sum 4 bits to variable

Posted: Sun Nov 11, 2012 1:21 pm
by Enamul
Hi,

Here is the corrected code..what Ben posted don't need to put in c code box rather in calculation box is ok. But you need to read input..anyway I have corrected the code.

Re: How do I sum 4 bits to variable

Posted: Mon Nov 12, 2012 7:44 am
by Dan81
Hello Markus

There no "special" fonction on RB3
if you can use RB3 for "D4", there will not be any calculation to do.
(Or I don"t understand the aim of your calculation. )

Daniel