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

What is Bit Masking?

Câu trả lời

Bit masking is a technique used in computer programming to manipulate specific bits within a binary number. It involves applying a mask to a value to keep, change, or clear certain bits. This is achieved using bitwise operations such as AND, OR, XOR, and NOT.

Key Concepts of Bit Masking

  1. Mask Definition: A mask is a binary number that specifies which bits in another binary number should be kept, changed, or cleared. For example, a mask of 00001111 would focus on the lower four bits of a byte.

  2. Bitwise Operations:

    • AND (&): Used to clear bits. Only the bits that are 1 in both the mask and the value remain 1.
    • OR (|): Used to set bits. Any bit that is 1 in the mask will be set to 1 in the value.
    • XOR (^): Used to toggle bits. Bits that are 1 in the mask will be flipped in the value.
    • NOT (~): Used to invert bits. All 0s become 1s and all 1s become 0s.

Examples of Bit Masking Operations

  1. Setting a Bit:
    To set a specific bit to 1, use the OR operation with a mask that has a 1 at the bit position you want to set.

    value |= (1 << bit_position);

    Example: To set the 3rd bit of 01000010:

    01000010
    OR
    00001000
    ------
    01001010
  2. Clearing a Bit:
    To clear a specific bit to 0, use the AND operation with a mask that has a 0 at the bit position you want to clear.

    value &= ~(1 << bit_position);

    Example: To clear the 3rd bit of 01001010:

    01001010
    AND
    11110111
    ------
    01000010
  3. Toggling a Bit:
    To toggle a specific bit, use the XOR operation with a mask that has a 1 at the bit position you want to toggle.

    value ^= (1 << bit_position);

    Example: To toggle the 3rd bit of 01000010:

    01000010
    XOR
    00001000
    ------
    01001010
  4. Checking a Bit:
    To check if a specific bit is set, use the AND operation with a mask that has a 1 at the bit position you want to check.

    bit = value & (1 << bit_position);

    Example: To check the 3rd bit of 01001010:

    01001010
    AND
    00001000
    ------
    00001000

Applications of Bit Masking

  • Optimization: Bit masking can replace more expensive operations with faster bit-level operations.
  • Memory Efficiency: It allows compact storage of data, such as using a single integer to repres...
middle

middle

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

middle

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

junior

What is a Byte?

middle

Explain how XOR (^) bit operator works

Bình luận

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

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