<bitset>
What is the size of char datatype in C++?
What is the size of bool datatype in C++?
Both take 1byte to store a value. Yes, bool datatype also takes 1byte.
What is the size of bool datatype in C++?
Both take 1byte to store a value. Yes, bool datatype also takes 1byte.
Bitset is a standard library available in c++ which allows us to store data in bitwise. The good thing was we can access each bit separately in a bitset as like elements in an array. Only change was we access them from the backside.
Eg: g = 00111011
then g[0]=g[1]=g[3]=g[4]=g[5]=1
and g[2]=g[6]=g[7]=0
It can be constructed[accepts] from Integer and Binary strings only. How many lines of code you write to convert a decimal to binary? .... It can be done in just 2 lines using the bitset.
#include <bitset>
#include <iostream>
using namespace std;
int main()
{
bitset<8> vin;
//here 'vin' will have all 8 bits unset as zero
// Value 8 inside angle brace denotes number of bits it can also be 16 or 32
bitset<8> tam(5);
//It will store number 5 as a bit stream in 'tam'
cout << vin.any() << endl;
cout << tam.any() << endl;
//It chk wheather there is atleast one 1 in the number; if so return 1 else 0
cout<<vin.all()<<endl;
cout<<tam.all()<<endl;
//It chk wheather all bits are set as 1; if so return 1 else 0
cout<<vin.none()<<endl;
//It returns true, if none of the bit is set as 1
cout<<"Flipping all :"<<tam.flip()<<endl;
//All bits will be fliped
cout<<"Flipping 3rd bit alone :"<<tam.flip(3)<<endl;
//3rd bit alone fliped
//changes are made permanent in source
cout<<"Set all :"<<vin.set()<<endl;
cout<<"Reset all :"<<vin.reset()<<endl;
cout<<"Set 5th bit alone :"<<vin.set(5)<<endl;
cout<<"Reset 5th bit alone :"<<vin.reset(5)<<endl;
cout<<"count 1's in bitset :"<<vin.count() <<endl;
//count returns number of 1 bits in bitset
cout<<"Size of inb :"<<vin.size()<<endl;
//no. of bits in vin
cout<<"count 0's in bitset :"<<vin.size() -vin.count() <<endl;
//Subtracting the count of 1's from total bits
cout<<"Testing wheather 3rd bit is set :"<<tam.test(3)<<endl;
//returns 1 if it is set else 0
return 0;
}
Similarly,
vin.to_ulong() converts bitset to unsigned long integer.
vin.to_ullong() converts bitset to unsigned long long integer.
vin.to_string() converts bitset to unsigned long long integer.
Done.
Comments
Post a Comment