How do I sum 4 bits to variable

For C and ASSEMBLY users to post questions and code snippets for programming in C and ASSEMBLY. And for any other C or ASM course related questions.

Moderators: Benj, Mods

Post Reply
markus747
Posts: 33
Joined: Mon Jul 23, 2012 7:17 pm
Location: Petaluma california USA
Has thanked: 26 times
Been thanked: 2 times
Contact:

How do I sum 4 bits to variable

Post 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

User avatar
Benj
Matrix Staff
Posts: 15312
Joined: Mon Oct 16, 2006 10:48 am
Location: Matrix TS Ltd
Has thanked: 4803 times
Been thanked: 4314 times
Contact:

Re: How do I sum 4 bits to variable

Post 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;

markus747
Posts: 33
Joined: Mon Jul 23, 2012 7:17 pm
Location: Petaluma california USA
Has thanked: 26 times
Been thanked: 2 times
Contact:

Re: How do I sum 4 bits to variable

Post 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
Attachments
lateral cleaner_1.fcf
(14.42 KiB) Downloaded 648 times

markus747
Posts: 33
Joined: Mon Jul 23, 2012 7:17 pm
Location: Petaluma california USA
Has thanked: 26 times
Been thanked: 2 times
Contact:

Re: How do I sum 4 bits to variable

Post by markus747 »

This one is even better.
Attachments
lateral cleaner_2.fcf
(14.69 KiB) Downloaded 651 times

User avatar
Enamul
Posts: 1772
Joined: Mon Mar 05, 2012 11:34 pm
Location: Nottingham, UK
Has thanked: 271 times
Been thanked: 814 times
Contact:

Re: How do I sum 4 bits to variable

Post 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.
Attachments
lateral cleaner_3.fcf
(18.5 KiB) Downloaded 658 times
Enamul
University of Nottingham
enamul4mm@gmail.com

User avatar
Dan81
Valued Contributor
Valued Contributor
Posts: 268
Joined: Sun Jan 15, 2006 4:07 pm
Location: Albi France
Been thanked: 60 times
Contact:

Re: How do I sum 4 bits to variable

Post 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
Attachments
lateral cleaner_4.fcf
(16.28 KiB) Downloaded 637 times

Post Reply