A2oz

How to Calculate the Bitwise AND of Two Numbers?

Published in Computer Science 2 mins read

The bitwise AND operation compares the corresponding bits of two numbers. If both bits are 1, the result is 1; otherwise, it's 0.

Here's a breakdown:

Understanding Bitwise AND

  • Binary Representation: Numbers are converted to their binary form (base-2). Each digit in a binary number represents a power of 2.
  • Bitwise Operation: The AND operation is applied to each corresponding bit position of the two numbers.
  • Result: The resulting binary number represents the bitwise AND of the original numbers.

Example

Let's calculate the bitwise AND of 5 and 3:

  1. Binary Representation:

    • 5 = 101 (binary)
    • 3 = 011 (binary)
  2. Bitwise AND:

    101
    011
    ---
    001
  3. Result:

    • 001 (binary) = 1 (decimal)

Therefore, the bitwise AND of 5 and 3 is 1.

Practical Applications

Bitwise AND is used in various programming scenarios, such as:

  • Checking Bits: To determine if a specific bit in a number is set (1).
  • Masking: To extract specific bits from a number.
  • Setting Bits: To selectively turn on specific bits in a number.

Conclusion

The bitwise AND operation is a fundamental concept in computer programming, allowing you to manipulate individual bits within numbers. Understanding this operation is crucial for working with data at the bit level.

Related Articles