The << and >> operators will shift a number bitwise to the left or right. If you want to display, for example, the rightmost bit, you could bitwise and (&) the number with a bitmask (like 0x0001).
so you would have:
1 2
int x = 0x1;
x << 1;
will result in x = 0x2.
To flip a bit, simply use bitwise not (~) or xor the the byte with a mask (^).
Tell me what you want to do with it, and I'll show you. If you want to display the nth bit, you could do this:
1 2 3 4 5
//displays nth bit of byte
int byte = 0xABCD;
int n = 9; //change this to whichever bit you want to view
cout << ((byte >> (n-1)) & 0x1);
If you want to flip the nth bit, you could do this:
1 2 3 4 5
//flips nth bit of byte
int byte = 0xABCD;
int n = 9; //change this to whichever bit you want to flip
byte = (byte ^ (0x1 << (n-1));
Basically you can use the bitwise operators:
<< >> & | ~ ^
and hex masks:
0xFFFF
0x0
0x1 << n
and ~(0x1 << n)
to do anything you would want with your byte.
@RPG....
how about like a vector its dynamic, reads all the bits (grows/shrinks according) displays all bits; side topic, i need something, literature to help me plan how to solve a problem (break it down). then i can code it from there
int byte = 0xAB;
vector <bool> bits;
//reads all bits
for (int i=0; i<8; i++)
bits.push_back((byte >> i) & 0x1);
//displays bits from left to right
for (int i=7; i>=0; i--)
cout << bits[i];
#include <bitset>
#include <iostream>
int main()
{
unsignedchar val = '\x1a';
std::bitset<8> b(val);
// iterate and change
for(size_t n = 0; n < b.size(); ++n)
b[n] = ~b[n];
// could also work with the whole thing
b = ~b;
// print
std::cout << b << '\n';
}
Also remember there's a special template specialization for vector<bool> where they are stored as bits, not bools. So the solution is (space) efficient.