• Welcome to our site! Electro Tech is an online community (with over 170,000 members) who enjoy talking about and building electronic circuits, projects and gadgets. To participate you need to register. Registration is free. Click here to register now.

Using an 8 bit register like a bit in C code?

Status
Not open for further replies.

Flyback

Well-Known Member
Hello,
We are using microchip XC8 free c compiler within mplab.x. We are programming PIC18F65K22.
We have two 8 bit registers dipsw2 and dipsw3 which are declared with the uint8_t type declaration.
Dipsw2 and dipsw3 only ever hold the value 0 or 1. (0x00 or 0x01)
Is the following type of comparison statement valid?

if (!dipsw2 && dipsw3) {currentint = 4;}

We believe this means, “if dipsw2 contains zero, and dipsw3 is non zero, then currentint register gets the value 4.”
This is treating the register rather like it’s a bit, but will this work?
 

misterT

Well-Known Member
Most Helpful Member
Yes, that is correct, but I would add some parenthesis.. just in case..

if ((!dipsw2) && (dipsw3)) {currentint = 4;}

And because I work with safety critical products, I would even consider writing:

if ((0 == dipsw2) && (1 == dipsw3)) { currentint = 4; }

.. but yes, your original code is also correct.
 

Flyback

Well-Known Member
thanks, but I am wondering, surely if dipsw3 contains 00000001, then !dipsw3 is 11111110 ...and not 00000000?
-its strange but asking the question kind of triggered this off in my head
 

misterT

Well-Known Member
Most Helpful Member
Exclamation mark (!) is a logical negation. It makes "true"->"false" and vice versa.
Tilde (~) is a bitwise negation. It flips every individual bit.. 1->0 and 0->1.

So, "!dipsw2" is correct. Tilde does what you describe in post #3 and would be incorrect in this case.
 
Last edited:
Status
Not open for further replies.

Latest threads

EE World Online Articles

Loading

 
Top