Using a regiater like a bit in c programming?

Status
Not open for further replies.
T

treez

Guest
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?
 

in C 0 is false and any none 0 value is taken as true so you statement should work OK

you can always test it with a simple program using the MPLABX simulator
 
Reactions: treez

    T

    Points: 2
    Helpful Answer Positive Rating
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
 

! is logical NOT (if TRUE result becomes False) - if dipsw3 contains 00000001, then !dipsw3 is 0

you are thinkng of ~ which is bitwise NOT or complement

run a program like this in the simulator - try changing values see what happens
Code:
#include <xc.h>        /* XC8 General Include File */
#pragma config XINST = OFF 
void main(void)
{
    unsigned char dipsw2=0,  dipsw3=1,  currentint = 0, j;
    if (!dipsw2 && dipsw3) {currentint = 4;}
    j=!dipsw3;
    j=~dipsw3;

what do you think the result of this is?
Code:
    unsigned char dipsw2=0,  dipsw3=1;
   if (~dipsw2 & dipsw3) {currentint = 6;}
 
Last edited:
Reactions: treez

    T

    Points: 2
    Helpful Answer Positive Rating
correct
in normal control structures one would use logical operators !, ||, &&

the bitwise operators ~ | & ^ are useful for testing individual bits in particular when checking the status registers of IO devices
 

Status
Not open for further replies.
Cookies are required to use this site. You must accept them to continue using the site. Learn more…