Low Level Bit Hacks You Absolutely Must Know - good coders code, great reuse
Check if the integer is even or odd.
if ((x & 1) == 0) {
x is even
}
else {
x is odd
}
Bit Hack #2. Test if the n-th bit is set.
if (x & (1<<n)) {
n-th bit is set
}
else {
n-th bit is not set
}
Bit Hack #3. Set the n-th bit.
y = x | (1<<n)
Bit Hack #4. Unset the n-th bit.
y = x & ~(1<<n)
Bit Hack #5. Toggle the n-th bit.
y = x ^ (1<<n)
Bit Hack #6. Turn off the rightmost 1-bit.
y = x & (x-1)
Read full article from Low Level Bit Hacks You Absolutely Must Know - good coders code, great reuse
Check if the integer is even or odd.
if ((x & 1) == 0) {
x is even
}
else {
x is odd
}
Bit Hack #2. Test if the n-th bit is set.
if (x & (1<<n)) {
n-th bit is set
}
else {
n-th bit is not set
}
Bit Hack #3. Set the n-th bit.
y = x | (1<<n)
Bit Hack #4. Unset the n-th bit.
y = x & ~(1<<n)
Bit Hack #5. Toggle the n-th bit.
y = x ^ (1<<n)
Bit Hack #6. Turn off the rightmost 1-bit.
y = x & (x-1)
Read full article from Low Level Bit Hacks You Absolutely Must Know - good coders code, great reuse