Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

bitwise magic #62

Merged
merged 1 commit into from
May 22, 2024
Merged

bitwise magic #62

merged 1 commit into from
May 22, 2024

Conversation

prosviriakova
Copy link
Contributor

Binary Representation of Powers of 2:

Numbers that are powers of 2 have exactly one bit set to 1 in their binary representation.

Examples:

  • 1 (2^0): 0001
  • 2 (2^1): 0010
  • 4 (2^2): 0100
  • 8 (2^3): 1000

Subtracting 1 from a Power of 2:

When you subtract 1 from a power of 2, all bits after the single 1 bit are flipped.

Examples:

  • 2 (0010) - 1 = 1 (0001)
  • 4 (0100) - 1 = 3 (0011)
  • 8 (1000) - 1 = 7 (0111)

Bitwise AND Operation:

The bitwise AND operation compares each bit of n and n-1:

If n is a power of 2:

The result of n & (n - 1) is 0 because there are no overlapping 1 bits.

Examples:

  • 4 (0100) & 3 (0011) = 0000
  • 8 (1000) & 7 (0111) = 0000

If n is not a power of 2:

The result of n & (n - 1) is not 0 because there are overlapping 1 bits.

Examples:

  • 6 (0110) & 5 (0101) = 0100
  • 10 (1010) & 9 (1001) = 1000

@pasqualerossi pasqualerossi merged commit 82fa0b9 into pasqualerossi:main May 22, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

2 participants