Reputation: 5
int main()
{
cout << hex;
cout << (0xe & 0x3); // 1110 & 0011 -> 0010 (AND)
cout << endl;
cout << (0xe | 0x3); // 1110 | 0011 -> 1111 (OR)
cout << endl;
cout << (0xe ^ 0x3); // 1110 ^ 0011 -> 1101 (XOR)
return 0;
}
When using cout, it displays the translation (2, f, and d) vs the actual value (0010, 1111, and 1101). How do I make it so that it display this vs what the bit goes with?
Upvotes: 1
Views: 219
Reputation: 30453
For example:
#include <iostream>
#include <string>
using namespace std;
string convBase(unsigned long v, long base) {
if (base < 2 || base > 16) return "Error: base out of range;";
string result;
string digits = "0123456789abcdef";
do {
result = digits[v % base] + result;
v /= base;
} while (v);
return result;
}
int main(int argc, char** argv) {
int a = 0xe;
int b = 0x3;
cout << hex;
cout << (a & b) << " - " << convBase(a & b, 2);
cout << endl;
cout << (a | b) << " - " << convBase(a | b, 2);
cout << endl;
cout << (a ^ b) << " - " << convBase(a ^ b, 2);
cout << endl;
return 0;
}
Output:
2 - 10 f - 1111 d - 1101
Upvotes: 1
Reputation: 726599
These are the correct values for the hex
representation of the binary values that you have requested: 0010
is 2, 1111
is f, and 1101
is d.
If you would like to print a binary representation, you can borrow convBase
function from here, or build your own.
cout << convBase((0xe & 0x3), 2); // 1110 & 0011 -> 0010 (AND)
cout << endl;
cout << convBase((0xe | 0x3), 2); // 1110 | 0011 -> 1111 (OR)
cout << endl;
cout << convBase((0xe ^ 0x3), 2); // 1110 ^ 0011 -> 1101 (XOR)
Upvotes: 3