C++ Program to Illustrate Usage of Bitset

This C++ program illustrates the usage of bitset. The bitset stores bits in the form 1s and 0s which emulates true and false. This class is optimized for space allocation and each of element of it occupies only one bit. The program uses several common bitset operations and functions.

Here is the source code of the C++ program which illustrates the usage of bitset. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.

  1. /*
  2.  * C++ Program to Illustrate usage of bitset
  3.  */
  4. #include <iostream>
  5. #include <bitset>
  6.  
  7. int main()
  8. {
  9.     std::bitset <5> a, b;
  10.  
  11.     b.set();
  12.     for (int i = 0; i < 5 ;i++)
  13.     {
  14.         if (i % 2 == 0)
  15.             a[i].flip();
  16.     }
  17.     std::cout << "Bitset a: " << a << std::endl;
  18.     std::cout << "Bitset b: " << b << std::endl;
  19.     std::cout << std::endl;
  20.     std::cout << "a XOR b = " << (a ^ b) << std::endl;
  21.     std::cout << "a AND b = " << (a & b) << std::endl;
  22.     std::cout << "a OR b  = " << (a | b) << std::endl;
  23.     std::cout << " NOT(a) = " << (~a) << std::endl;
  24. }

$ a.out
Bitset a: 10101
Bitset b: 11111
 
a XOR b = 01010
a AND b = 10101
a OR b  = 11111
 NOT(a) = 01010

Sanfoundry Global Education & Learning Series – 1000 C++ Programs.

advertisement
advertisement
If you wish to look at all C++ Programming examples, go to C++ Programs.

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.