Created
January 22, 2026 14:27
-
-
Save ABB00717/98a5d9b1ffabf5e3235f21a8667d7211 to your computer and use it in GitHub Desktop.
An `and` bitwise operation using only integer arithmetics.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // Credit goes to https://haqr.eu/tinycompiler/afterword/ | |
| /* | |
| * CONCEPT: | |
| * 1. Sign Bit Handling (MSB): | |
| * Since standard integers are signed (2's complement), negative numbers | |
| * would break the 'while (a > 0)' loop condition. We treat the 32nd bit | |
| * (the sign bit, value 2^31 or 2147483648) separately. We manually check | |
| * it, strip it to make the numbers positive, and re-apply it to the result | |
| * if necessary. | |
| * | |
| * 2. Lower 31 Bits Processing: | |
| * Once inputs are positive, we iterate through the bits from Least | |
| * Significant (LSB) to Most Significant. We use Modulo 2 to check if a bit | |
| * is 1, and Division by 2 to shift right. | |
| */ | |
| int and(int a, int b) { | |
| int result; | |
| int pow; | |
| result = 0; | |
| if (a<0 && b<0) { | |
| result = -2147483648; | |
| } | |
| if (a<0) { | |
| a = a + 2147483648; | |
| } | |
| if (b<0) { | |
| b = b + 2147483648; | |
| } | |
| pow = 1; | |
| while a>0 || b>0 { | |
| if a % 2 == 1 && b % 2 == 1 { | |
| result = result + pow; | |
| } | |
| a = a / 2; | |
| b = b / 2; | |
| pow = pow * 2; | |
| } | |
| return result; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment