Câu hỏi phỏng vấn Bit Manipulation
Câu hỏi

Explain how XOR (^) bit operator works

Câu trả lời

The XOR (exclusive OR) bitwise operator, denoted by the caret symbol (^), is a binary operator that performs a logical exclusive OR operation on each pair of corresponding bits of two operands. The result of the XOR operation is 1 if the corresponding bits of the operands are different, and 0 if they are the same.

How XOR Works

  1. Basic Operation:

    • The XOR operator compares each bit of the first operand to the corresponding bit of the second operand.
    • If the bits are different, the result bit is set to 1.
    • If the bits are the same, the result bit is set to 0.

    The truth table for XOR is as follows:

    x y x ^ y
    0 0 0
    0 1 1
    1 0 1
    1 1 0
  2. Example:

    • Consider the numbers 5 (binary 0101) and 3 (binary 0011).

    • Performing XOR on these numbers:

      0101 (5)
      ^ 0011 (3)
      ------
      0110 (6)
    • The result is 6 (binary 0110) because the bits differ in the second and third positions.

  3. Properties of XOR:

    • Identity: $$ x \oplus 0 = x $$
    • Self-inverse: $$ x \oplus x = 0 $$
    • Commutative: $$ x \oplus y = y \oplus x $$
    • Associative: $$ (x \oplus y) \oplus z = x \oplus (y \oplus z) $$
  4. Applications:

    • Swapping Values: XOR can be used to swap two variables without using a temporary variable.
      function swapWithXOR(a, b) {
        a = a ^ b;
        b = a ^ b;
        a = a ^ b;
        console.log("a: " + a + ", b: " + b);
      }
      swapWithXOR(4, 1); // a: 1, b: 4
    • Finding Odd Occurrences: XOR is useful in problems where you need to find the element that appears an odd number of times in an array.
    • Cryptography: XOR is used in simple encryption algorithms like the XOR cipher.

Special Cases

  1. XOR with Negative Numbers:
    • When dealing with negative numbers, the XOR operation considers the two's complement representation of the numbers.
    • Example: $$ -4 \oplus -2 $$
      • Convert to binary and find the two's complement:
        -4: 1000 0100 (binary), two's complement: 1111 1100
        -2: 1000 0010 (binary), two's co...
middle

middle

Gợi ý câu hỏi phỏng vấn

middle

What are some real world use cases of the bitwise operators?

junior

Name some bitwise operations you know

junior

What is a Byte?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào