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

Name some bitwise operations you know

Câu trả lời

Bitwise operations are fundamental operations that directly manipulate individual bits of binary numbers. Here are some common bitwise operations:

1. Bitwise AND (&)

  • Description: Takes two binary numbers and performs a logical AND operation on each pair of corresponding bits. The result is 1 only if both bits are 1.
  • Example:

    12 \& 25 \rightarrow 00001100 \& 00011001 = 00001000 \text{ (8 in decimal)}

  • Use Case: Often used for bit masking to check if specific bits are set.

2. Bitwise OR (|)

  • Description: Takes two binary numbers and performs a logical OR operation on each pair of corresponding bits. The result is 1 if at least one of the bits is 1.
  • Example:

    12 | 25 \rightarrow 00001100 | 00011001 = 00011101 \text{ (29 in decimal)}

  • Use Case: Used to set specific bits in a number.

3. Bitwise XOR (^)

  • Description: Takes two binary numbers and performs a logical XOR operation on each pair of corresponding bits. The result is 1 if the bits are different.
  • Example:

    12 \oplus 25 \rightarrow 00001100 \oplus 00011001 = 00010101 \text{ (21 in decimal)}

  • Use Case: Used in algorithms for swapping values without a temporary variable and for error detection in data transmission.

4. Bitwise NOT (~)

  • Description: Takes a single binary number and inverts all the bits (0 becomes 1 and 1 becomes 0).
  • Example:

    \sim 12 \rightarrow \sim 00001100 = 11110011 \text{ (-13 in decimal, considering two's complement representation)}

  • Use Case: Used to flip all bits in a number.

5. Left Shift (<<)

  • Description: Shifts the bits of a number to the left by a specified number of positions. Each shift to the left is equivalent to multiplying the number by 2.
  • Example:

    12 << 2 \rightarrow 00001100 << 2 = 00110000 \text{ (48 in decimal)}

  • Use Case: Used for efficient multiplication by powers of 2.

6. Right Shift (>>)

  • Description: Shifts the bits of a number to the right by a specified number of pos...
junior

junior

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

middle

What is Bit Masking?

entry

What is Bit?

junior

Explain what is Bitwise operation?

Bình luận

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

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