Back to TILs

C++ bitwise operator

Date: 2023-02-20Last modified: 2024-11-02

Table of contents

  unsigned char value1{0b01010101};
  unsigned char value2{0b11110000};
  unsigned char value3{0};

  auto print3 = [](auto value1, auto value2, auto value3, auto label) {
    auto print1 = [](auto value) { cout << '\n' << std::bitset<8>(value); };
    print1(value1);
    print1(value2);
    cout << "\n-------- " << label;
    print1(value3);
    cout << '\n';
  };

  auto printUnary = [](auto value1, auto value2, auto label) {
    auto print1 = [](auto value) { cout << '\n' << std::bitset<8>(value); };
    print1(value1);
    cout << "\n-------- " << label;
    print1(value2);
    cout << '\n';
  };

  print3(value1, value2, value1 ^ value2, "^ XOR");  // ZOR
  print3(value1, value2, value1 | value2, "| OR");
  print3(value1, value2, value1 & value2, "& AND");

  printUnary(value1, ~value1, "~ NOT");
  printUnary(value2, ~value2, "~ NOT");

  value3 = value1;
  value3 &= 0b10000;
  print3(value1, 0b10000, value3, " &= 0b10000 MASK");

  value3 = value1;
  value3 &= 0b1000;
  print3(value1, 0b1000, value3, " &= 0b01000 MASK");

  value3 = value1;
  value3 |= 0b10000;
  print3(value1, 0b10000, value3, " |= 0b10000 SET BIT TO 1");

  value3 = value1;
  value3 |= 0b1000;
  print3(value1, 0b1000, value3, " |= 0b01000 SET BIT TO 1");

  value3 = value1;
  value3 &= ~0b10000;
  print3(value1, ~0b10000, value3, " &= ~0b10000 SET BIT TO 0");

  value3 = value1;
  value3 &= ~0b1000;
  print3(value1, ~0b1000, value3, " &= ~0b01000 SET BIT TO 0");

  value3 = value1;
  value3 ^= 0b10000;
  print3(value1, 0b10000, value3, " ^= 0b10000");

  value3 = value1;
  value3 ^= 0b1000;
  print3(value1, 0b1000, value3, " ^= 0b01000");

  const unsigned int red_mask{0xff000000};
  const unsigned int green_mask{0x00ff0000};
  const unsigned int blue_mask{0x0000ff00};
  const unsigned int alpha_mask{0x000000ff};
  unsigned int my_color{0xAABCDEFF};

  cout << hex << showbase << endl;
  cout << "C: " << my_color << endl;
  cout << "R: " << ((my_color & red_mask) >> 24) << endl;
  cout << "G: " << ((my_color & green_mask) >> 16) << endl;
  cout << "B: " << ((my_color & blue_mask) >> 8) << endl;
  cout << "A: " << ((my_color & alpha_mask) >> 0) << endl;

Possible output


01010101
11110000
-------- ^ XOR
10100101

01010101
11110000
-------- | OR
11110101

01010101
11110000
-------- & AND
01010000

01010101
-------- ~ NOT
10101010

11110000
-------- ~ NOT
00001111

01010101
00010000
--------  &= 0b10000 MASK
00010000

01010101
00001000
--------  &= 0b01000 MASK
00000000

01010101
00010000
--------  |= 0b10000 SET BIT TO 1
01010101

01010101
00001000
--------  |= 0b01000 SET BIT TO 1
01011101

01010101
11101111
--------  &= ~0b10000 SET BIT TO 0
01000101

01010101
11110111
--------  &= ~0b01000 SET BIT TO 0
01010101

01010101
00010000
--------  ^= 0b10000
01000101

01010101
00001000
--------  ^= 0b01000
01011101

C: 0xaabcdeff
R: 0xaa
G: 0xbc
B: 0xde
A: 0xff

References