A2oz

What does Num & 1 do?

Published in Programming 2 mins read

In programming, the expression "Num & 1" is a bitwise AND operation. It's used to check if a number is even or odd.

Here's a breakdown:

  • Bitwise AND (&): This operator compares the binary representation of two numbers, bit by bit. If both bits at the corresponding positions are 1, the resulting bit is 1; otherwise, it's 0.
  • 1 in binary: The number 1 in binary is represented as 00000001.
  • How it works: When you perform "Num & 1," the binary representation of Num is compared to the binary representation of 1. If the least significant bit (LSB) of Num is 1, the result of the operation will also be 1, indicating that Num is odd. If the LSB of Num is 0, the result will be 0, indicating that Num is even.

Example:

Let's say Num is 5:

  • Decimal: 5
  • Binary: 00000101
  • 1 in Binary: 00000001
  • Result of 5 & 1: 00000001 (which is 1 in decimal)

Therefore, since the result is 1, 5 is an odd number.

Practical Insights:

  • Efficiency: This operation is very efficient and is often used to determine even or odd numbers in performance-critical applications.
  • Other uses: While commonly used to check for even or odd numbers, the bitwise AND operation has other applications in programming, like masking specific bits in a number or setting certain bits to 0.

Related Articles