CodexBloom - Programming Q&A Platform

Using Rust's core library for low-level bit manipulation, but encountering unexpected behavior

👀 Views: 114 đŸ’Ŧ Answers: 1 📅 Created: 2025-05-31
rust core bit-manipulation Rust

I've been banging my head against this for hours. I've been banging my head against this for hours. I'm working on a Rust project where I need to perform low-level bit manipulation using the core library. I'm using Rust 1.66 and specifically trying to create a function that shifts bits and checks for overflow conditions. I implemented a simple function like this: ```rust #![no_std] fn shift_and_check(value: u32, shift: u32) -> Result<u32, &'static str> { if shift >= 32 { return Err("Shift amount must be less than 32"); } let result = value << shift; if result < value { // This check is intended to catch overflow return Err("Overflow occurred"); } Ok(result) } ``` However, when I call this function with `shift_and_check(0xFFFFFFFE, 1)`, I expect it to return an overflow error, but it correctly returns `0xFFFFFFFC`. I thought the comparison `if result < value` would catch the overflow, but it seems to be incorrect. I also tried using the `checked_shl` method from the standard library, but since I'm using `#![no_std]`, that isn't an option. I've also experimented with the following: ```rust fn shift_and_check_v2(value: u32, shift: u32) -> Result<u32, &'static str> { if shift >= 32 { return Err("Shift amount must be less than 32"); } let result = value.wrapping_shl(shift); Ok(result) } ``` This version just wraps around without indicating an overflow. Can someone help clarify how to correctly check for overflow when shifting bits in this context? I'm also curious if there are recommended best practices for handling low-level bit manipulation in Rust, especially in `#![no_std]` environments. Thanks in advance for your help! I'm developing on CentOS with Rust.