I know @minomic, I also noticed that right away after writing the sentence and thought it was funny :p
What do you mean by base 2 @dhayden? You mean shifting? I understand that, >> divides and << does multiplications and the numbers used in the shifting are multiples of 2. That's made by moving the most significant bit to the right or to the left.
1 2
|
int calc = 8 >> 2;
cout << calc; // result = 2
|
I actually understand the concept of bitwise operations, my problem here is mostly about how are they used ("why", I already know why they're useful but I don't get how to actually use them). I already know how to convert "normal" integers to bits and I get all those 1's and 0's which have a meaning, what I want to know is how am I gonna use them.
Here is the example with the output in the book I'm using:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
|
#include <iostream>
#include <bitset>
using namespace std;
int main()
{
cout << “Enter a number (0 - 255): “;
unsigned short InputNum = 0;
cin >> InputNum;
bitset<8> InputBits (InputNum);
cout << InputNum << “ in binary is “ << InputBits << endl;
bitset<8> BitwiseNOT = (~InputNum);
cout << “Logical NOT |” << endl;
cout << “~” << InputBits << “ = “ << BitwiseNOT << endl;
cout << “Logical AND, & with 00001111” << endl;
bitset<8> BitwiseAND = (0x0F & InputNum);// 0x0F is hex for 0001111
cout << “0001111 & “ << InputBits << “ = “ << BitwiseAND << endl;
cout << “Logical OR, | with 00001111” << endl;
bitset<8> BitwiseOR = (0x0F | InputNum);
cout << “00001111 | “ << InputBits << “ = “ << BitwiseOR << endl;
cout << “Logical XOR, ^ with 00001111” << endl;
bitset<8> BitwiseXOR = (0x0F ^ InputNum);
cout << “00001111 ^ “ << InputBits << “ = “ << BitwiseXOR << endl;
return 0;
}
|
Output:
Enter a number (0 - 255): 181
181 in binary is 10110101
Logical NOT |
~10110101 = 01001010
Logical AND, & with 00001111
0001111 & 10110101 = 00000101
Logical OR, | with 00001111
00001111 | 10110101 = 10111111
Logical XOR, ^ with 00001111
00001111 ^ 10110101 = 10111010