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

What is difference between >> and >>> operators?

Câu trả lời

The >> and >>> operators are both right shift operators, but they differ in how they handle the sign bit of the number being shifted. Here is a detailed explanation of each:

>> Operator (Signed Right Shift)

The >> operator is known as the signed right shift operator. It shifts the bits of the number to the right by the specified number of positions. The key characteristic of the signed right shift is that it preserves the sign of the original number. This means that for positive numbers, it fills the vacated bit positions with zeros, and for negative numbers, it fills the vacated bit positions with ones (sign extension).

Example:

For a positive number:

  • 9 >> 2 $$ results in $$ 2

    • Binary: $$ 00000000000000000000000000001001 $$ (9)
    • After shift: $$ 00000000000000000000000000000010 $$ (2)

For a negative number:

  • -9 >> 2 $$ results in $$ -3

    • Binary: $$ 11111111111111111111111111110111 $$ (-9)
    • After shift: $$ 11111111111111111111111111111101 $$ (-3)

>>> Operator (Unsigned Right Shift)

The >>> operator is known as the unsigned right shift operator or zero-fill right shift. It shifts the bits of the number to the right by the specified number of positions, but it always fills the vacated bit positions with zeros, regardless of the sign of the original number. This means that the result is always a non-negative number.

Example:

For a positive number:

  • 9 >>> 2 $$ results in $$ 2

    • Binary: $$ 00000000000000000000000000001001 $$ (9)
    • After shift: $$ 00000000000000000000000000000010 $$ (2)

For a negative number:

  • -9 >>> 2 $$ results in $$ 1073741821

    • Binary: $$ 11111111111111111111111111110111 $$ (-9)
    • After shift: $$ 00111111111111111111111111111101 $$ (1073741821)

Key Differences:

  1. Sign Preservation:

    • >> preserves the sign of the original number (sign extension).
    • >>> does not preserve the sign and always fills the vacated positions with zeros (zero-fill).
  2. Resulting Value:

    • >> can result in negative numbers if the original number was negative.
    • >>> always results in a non-negative number...
middle

middle

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

middle

Explain how XOR (^) bit operator works

junior

What is a Byte?

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