vinothmct
Member level 1
- Joined
- May 2, 2012
- Messages
- 38
- Helped
- 1
- Reputation
- 2
- Reaction score
- 1
- Trophy points
- 1,288
- Activity points
- 1,584
How to check a bit in a variable whether it is set or not using C language
Follow along with the video below to see how to install our site as a web app on your home screen.
Note: This feature may not be available in some browsers.
bit bit_test(unsigned char Tval, unsigned char B) {
unsigned char TestVal=1;
TestVal=TestVal<<B;
if (Tval & TestVal)
return 1;
else
return 0;
}
Code C - [expand] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 // add this defines #define SETBIT(ADDRESS,BIT) (ADDRESS |= (1<<BIT)) #define CLEARBIT(ADDRESS,BIT) (ADDRESS &= ~(1<<BIT)) #define FLIPBIT(ADDRESS,BIT) (ADDRESS ^= (1<<BIT)) #define CHECKBIT(ADDRESS,BIT) (ADDRESS & (1<<BIT)) #define WRITEBIT(RADDRESS,RBIT,WADDRESS,WBIT) (CHECKBIT(RADDRESS,RBIT) ? SETBIT(WADDRESS,WBIT) : CLEARBIT(WADDRESS,WBIT)) // and then you can use SETBIT(PORTX,2); // set bit2 of portx (set to 1) SETBIT(PORTY,0); // set bit0 of porty CLEARBIT(PORTX,5); // clear bit5 of portx (set to 0) FLIPBIT(PORTX,2); // invert bit2 of portX, if it was 1 it becomes 0, and if 0 becomes 1 // example for portx 0x10101010 the result is 0x10101110 if (CHECKBIT(PORTX,4)) {} else {} // result is true if bit4 of portx is 1, false if it is 0 if (!CHECKBIT(PORTX,4)) {} else {} // result is true if bit4 of portx is 0, false if it is 1 WRITEBIT(PORTX,0,PORTY,2); // copy the bit0 of portx to bit2 of porty