Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,885 questions

51,811 answers

573 users

How to define and use bit fields in C

2 Answers

0 votes
#include <stdio.h>

struct 
{ 
	unsigned int f1 : 1; // 1 bit (1 / 0)
	unsigned int f2 : 1; // 1 bit (1 / 0)
	unsigned int f3 : 1; // 1 bit (1 / 0)
} flags; 

 
  
int main(void)
{

    // turn the bits on
	flags.f1 = flags.f2 = flags.f3 = 1;
	printf("%d %d %d\n", flags.f1, flags.f2, flags.f3);
	
    // turn the bits off
	flags.f1 = flags.f2 = flags.f3 = 0;
	printf("%d %d %d\n", flags.f1, flags.f2, flags.f3);
	
	if (flags.f1 == 0)
		printf("flag f1 is off\n");
  
    return 0;
}

 
/*
   
run:
   
1 1 1
0 0 0
flag f1 is off
   
*/

 



answered Jan 5, 2016 by avibootz
edited Jan 5, 2016 by avibootz
0 votes
#include <stdio.h>

struct 
{ 
	unsigned int f1 : 3; // 3 bits (from 000 to 111)
} flags;

 
int main(void)
{
	flags.f1 = 4;
	printf("flags.f1: %d\n", flags.f1);

	flags.f1 = 7;
	printf("flags.f1: %d\n", flags.f1);

	flags.f1 = 8; // warning 7 (111) is the max for 3 bits
	printf("flags.f1: %d\n", flags.f1);
	
    return 0;
}

 
/*
   
run:
   
flags.f1: 4
flags.f1: 7
flags.f1: 0
  
*/

 



answered Jan 5, 2016 by avibootz

Related questions

1 answer 213 views
213 views asked Aug 28, 2016 by avibootz
1 answer 116 views
1 answer 110 views
110 views asked May 10, 2022 by avibootz
1 answer 198 views
198 views asked Aug 28, 2016 by avibootz
1 answer 102 views
1 answer 138 views
...