1
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?

2 Answers 2

3

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) 
Sign up to request clarification or add additional context in comments.

2 Comments

How would I include the few 0's before the first 1? eg: 0010 instead of 10 for the first line.
@sfxworks You can use a combination of setfill and setw in <iomanip>, take a look at an example: link.
1

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

1 Comment

Maybe convBase(0, base) should be "0" instead of ""

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.