jhasuraj01's blog

By jhasuraj01, history, 7 days ago, In English

Bitwise AND, OR and XOR are bitwise operators in C++ and Python that perform operations on the binary representation of numbers.

Bitwise AND (&)

It compares each bit of the first operand to the corresponding bit of the second operand. If both bits are 1, the corresponding result bit is set to 1. Otherwise, the corresponding result bit is set to 0.

Example: In C++:

int x = 12;  // binary: 1100
int y = 15;  // binary: 1111
int z = x & y;  // binary: 1100, decimal: 12

In Python:

x = 12
y = 15
z = x & y
print(z)  # Output: 12

Bitwise OR (|)

It compares each bit of the first operand to the corresponding bit of the second operand. If at least one of the bits is 1, the corresponding result bit is set to 1. Otherwise, the corresponding result bit is set to 0.

Example: In C++:

int x = 12;  // binary: 1100
int y = 15;  // binary: 1111
int z = x | y;  // binary: 1111, decimal: 15

In Python:

x = 12
y = 15
z = x | y
print(z)  # Output: 15

Bitwise XOR (^)

It compares each bit of the first operand to the corresponding bit of the second operand. If the bits are different, the corresponding result bit is set to 1. Otherwise, the corresponding result bit is set to 0.

Example:

In C++:

int x = 12;  // binary: 1100
int y = 15;  // binary: 1111
int z = x ^ y;  // binary: 0011, decimal: 3

In Python:

x = 12
y = 15
z = x ^ y
print(z)  # Output: 3

It's worth noting that these operations are done on the binary level and are generally faster than doing the operations on the decimal level.

 
 
 
 
  • Vote: I like it
  • +4
  • Vote: I do not like it