Sobes.tech
Junior

What bitwise operations do you know?

sobes.tech AI

Answer from AI

  • & (bitwise AND): Compares bits in each position and returns 1 if both bits are 1.
  • | (bitwise OR): Compares bits in each position and returns 1 if at least one bit is 1.
  • ^ (bitwise XOR): Compares bits in each position and returns 1 if the bits are different.
  • ~ (bitwise NOT): Inverts each bit of the operand.
  • << (left shift): Shifts the bits of the operand to the left by the specified number of positions. The freed right bits are filled with zeros.
  • >> (right shift with sign extension): Shifts the bits of the operand to the right by the specified number of positions. The freed left bits are filled with the sign bit (0 for positive, 1 for negative).
  • >>> (unsigned right shift): Shifts the bits of the operand to the right by the specified number of positions. The freed left bits are filled with zeros.

Examples:

// Bitwise AND
int a = 5;  // 0101 in binary
int b = 3;  // 0011 in binary
int resultAnd = a & b; // 0001 (1 in decimal)

// Bitwise OR
int resultOr = a | b; // 0111 (7 in decimal)

// Bitwise XOR
int resultXor = a ^ b; // 0110 (6 in decimal)

// Bitwise NOT
int c = -15; // Example for a negative number, representation depends on the system (two's complement)
int resultNot = ~c; // Inverts all bits

// Left shift
int d = 2; // 0010 in binary
int resultLeftShift = d << 2; // 1000 (8 in decimal)

// Right shift with sign extension
int e = 10; // 1010 in binary
int resultRightShift = e >> 2; // 0010 (2 in decimal)

int f = -10; // Example for a negative number
int resultSignedRightShift = f >> 2; // Result depends on the representation

// Unsigned right shift
int g = -10; // Example for a negative number
int resultUnsignedRightShift = g >>> 2; // Fills with zeros on the left, regardless of the sign