Power of Two Check Implementation in Rust
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓Power of Two Check runs in O(1) time and O(1) space, in Rust as in every other language.
- ✓is_power_of_two() is an inherent method on every unsigned integer type, u8 through u128 plus usize, and it lives in core, so it needs no import and works under #![no_std].
- ✓A reviewer deletes a hand-rolled n & (n - 1) == 0 and writes n.is_power_of_two(), because the stdlib method is const, inlined, and already documented to answer false for zero.
- ✓The Rust trap: Subtracting one from an unsigned zero is not a wraparound in Rust, it is a decision the build profile makes for you: debug panics with 'attempt to subtract with overflow', release wraps to u32::MAX.
- ✓is_power_of_two() lowers to an AND, a subtract and a compare, with no bounds check, no allocation and no dynamic dispatch; LLVM recognises the pattern and folds it.
What Power of Two Check actually is
Power of Two Check in Rust: what you actually reach for
Rust implementation
fn hand_rolled(n: u32) -> bool {
// wrapping_sub, because plain `-` panics in debug on n == 0
n != 0 && n & n.wrapping_sub(1) == 0
}
fn signed_is_pow2(n: i64) -> bool {
// TryFrom turns the negative case into Err instead of a reinterpreted sign bit
u64::try_from(n).map_or(false, u64::is_power_of_two)
}
fn main() {
// Inherent method: no import, const, and works in no_std
assert!(1024u32.is_power_of_two());
assert!(!0u32.is_power_of_two());
assert!((1u128 << 100).is_power_of_two());
assert!(hand_rolled(1024));
assert!(!hand_rolled(0));
assert!(signed_is_pow2(64));
assert!(!signed_is_pow2(-64));
assert_eq!(1000u32.next_power_of_two(), 1024);
assert_eq!(u32::MAX.checked_next_power_of_two(), None);
assert_eq!(1024u32.count_ones(), 1);
assert_eq!(1024u32.trailing_zeros(), 10);
}
Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe Rust-specific trap
Performance in Rust, beyond the O(1)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which Rust type or library should I use for Power of Two Check?
is_power_of_two() is an inherent method on every unsigned integer type, u8 through u128 plus usize, and it lives in core, so it needs no import and works under #![no_std]. Beside it sit next_power_of_two(), the non-panicking checked_next_power_of_two(), count_ones(), leading_zeros() and trailing_zeros(). There is deliberately no is_power_of_two on the signed types: convert with u64::try_from(x) and let the negative case become an Err rather than a reinterpreted sign bit. NonZeroU32 and its siblings carry the non-zero invariant in the type when callers upstream need it.
What is the most common Rust mistake when implementing Power of Two Check?
Subtracting one from an unsigned zero is not a wraparound in Rust, it is a decision the build profile makes for you: debug panics with 'attempt to subtract with overflow', release wraps to u32::MAX. So the hand-rolled 0 & (0 - 1) == 0 crashes your test suite and returns true, the wrong answer, in production. Use wrapping_sub or the stdlib method. Shifts carry the same asymmetry: 1u32 << k with k equal to 32 panics in debug and masks the shift amount to five bits in release, yielding 1, so building the value under test by shifting is unsafe at the width boundary.
How does Power of Two Check actually perform in Rust?
is_power_of_two() lowers to an AND, a subtract and a compare, with no bounds check, no allocation and no dynamic dispatch; LLVM recognises the pattern and folds it. count_ones() becomes a single POPCNT instruction only when the target enables the feature, meaning x86-64-v2 or -C target-feature=+popcnt; on baseline x86-64 it expands to the software popcount sequence of roughly a dozen instructions. Debug builds insert an overflow check around every hand-rolled subtraction, which is why cargo test timings and cargo test --release timings diverge so sharply here. Time complexity is O(1) and space is O(1).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialIf you are a student, see what Devin offers students for free on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.