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;
}

cout を使用すると、変換 (2、f、および d) と実際の値 (0010、1111、および 1101) が表示されます。これとビットの内容を表示するにはどうすればよいですか?

4

2 に答える 2

3

これらは、hex要求したバイナリ値の表現の正しい値です: 0010is 2、1111is f、および1101is d。

バイナリ表現を印刷したい場合は、 hereconvBaseから関数を借りるか、独自に構築できます。

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)
于 2012-07-27T02:57:09.270 に答える
1

例えば:

#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;
}

出力:

2 - 10 f - 1111 d - 1101

于 2012-07-27T03:22:02.193 に答える