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?
 
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.
 
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
 
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.
Cookies are required to use this site. You must accept them to continue using the site. Learn more…