Skip to contentSaltar al contenido
125+ QA and SEO checks per page

Power of Two Check Implementation in Rust

11 min readbeginner
Website QA and SEO audits

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

A power-of-two test asks whether a positive integer has exactly one bit set: 1, 2, 4, 8, 16, and so on. The standard trick is n > 0 combined with n & (n - 1) == 0, because subtracting one flips the lowest set bit and every bit below it, so the AND clears to zero only when there was a single set bit to begin with. Engineers reach for it when sizing hash tables, ring buffers and allocator blocks, where a power-of-two capacity turns an expensive modulo into a cheap mask (i & (cap - 1)), and when validating an alignment argument before handing it to a lower layer.

Power of Two Check in Rust: what you actually reach for

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.

Rust implementation

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. If the value must stay signed, they want u32::try_from(n).map_or(false, u32::is_power_of_two) rather than an `as` cast, since `as` on a negative i32 silently reinterprets the sign bit. Any hand-rolled arithmetic on an unsigned type must use wrapping_sub instead of the plain minus.
rust
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 Free

The Rust-specific 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. 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.

Performance in Rust, beyond the O(1)

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. The asymptotic cost is the same in every language, O(1) time and O(1) space describe the algorithm, not the runtime, so these constant factors and allocation patterns are the part that actually differs when you port Power of Two Check between languages.

Real-World Applications

Power of Two Check applies wherever its problem shape appears in your own code. In Rust, check whether the standard library or a well maintained package already provides it before you write your own. Understanding Power of Two Check helps you reason about the tools you use daily and make better architectural decisions in your own projects.

Interview Tips & Practice

Power of Two Check appears frequently in phone screens and early-round coding interviews. When presenting your solution: (1) clarify the problem constraints before coding, (2) explain your approach verbally including why you chose Power of Two Check over alternatives, (3) implement step by step with clean variable names, (4) analyze time and space complexity explicitly, and (5) discuss optimizations and trade-offs. Common follow-up questions include: Can you optimize the space complexity? How does this handle concurrent access? What if the input does not fit in memory? Practice variations of Power of Two Check to build pattern recognition. In Rust, demonstrate proficiency with ownership system and pattern matching to show language mastery alongside algorithmic thinking. Companies value candidates who write idiomatic Rust code that is both correct and maintainable.

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).

Share this article

🔥 Enjoyed this? Share with someone who'd love it

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 trial

If you are a student, see what Devin offers students for free on Noizz.

Is YOUR site's SEO this optimized?

Find out in 60 seconds with a free QA audit.

Free SEO Check

Is your site built to last?

Run a free QA audit and get your Site Health Score in seconds.

Check Your Site Free

No signup required

Thousands of audits runAverage 23-point score improvement95% fix success rateAudit yours

How does your site compare?

Paste your URL below. Get a complete QA report with SEO score, accessibility issues, security checks, and a one-click fix prompt. Free. No signup.

Takes 30 seconds. No signup. Generates a fix-everything prompt.

Explore More Topics

Engagement

0

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.