Continue to Site

Welcome to EDAboard.com

Welcome to our site! EDAboard.com is an international Electronics Discussion Forum focused on EDA software, circuits, schematics, books, theory, papers, asic, pld, 8051, DSP, Network, RF, Analog Design, PCB, Service Manuals... and a whole lot more! To participate you need to register. Registration is free. Click here to register now.

How to check how a bit is set in c?

Status
Not open for further replies.

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
 

This is what I use for 8-bit testing.

Code:
bit bit_test(unsigned char Tval, unsigned char B) {

	unsigned char TestVal=1;
	
	TestVal=TestVal<<B;
	
	if (Tval & TestVal)
		return 1;
	else
		return 0;
}
 

A set of macro can do that without spending any resources


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



All the examples are for ports but they work for variables too
 
Status
Not open for further replies.

Similar threads

Part and Inventory Search

Welcome to EDABoard.com

Sponsor

Back
Top