If you're interested in setting/clearing/accessing very simply specific bits, you could consider std::bitset
:
bitset<8> s; // bit set of 8 bits
s[3]=a; // access individual bits, as if it was an array
s[2]=b;
s[1]=c;
s[0]=d; // the first bit is the least significant bit
cout << s <<endl; // streams the bitset as a string of '0' and '1'
cout << "0x"<< hex << s.to_ulong()<<endl; // convert the bitset to unsigned long
cout << s[3] <<endl; // access a specific bit
cout << "Number of bits set: " << s.count()<<endl;
Online demo
The advantage is that the code is easier to read and maintain, especially if you're modifying bitmapped data. Because setting specific bits using binary arithmetics with a combination of <<
and |
operators as explained by Anttii is a vorkable solution. But clearing specific bits in an existing bitmap, by combining the use of <<
and ~
(to create a bit mask) with &
is a little more tricky.
Another advantage is that you can easily manage large bitsets of hundreds of bits, much larger than the largest built-in type unsigned long long
(although doing so will not allow you to convert as easily to an unsigned long or an unsigned long long: you'll have to go via a string).