Search code examples
rustbitwise-operatorsbit-shift

Rust bitwise operations


I am currently trying to convert a hexadecimal value in rust (as a u16) to a RGB value stored as separate variables, all of type u8. The way I decided to do this was to use bitwise operators to get the separate values from the hex with this code:

Color::RGB(((hex >> (16u8)) & 0xFF) as u8, ((hex >> (8u8)) & 0xFF) as u8, ((hex) & 0xFF) as u8)

which resulted in an error:

error: this arithmetic operation will overflow
  --> src/style.rs:50:21
   |
50 |         Color::RGB(((hex >> (16u8)) & 0xFF) as u8, ((hex >> (8u8)) & 0xFF) as u8, ((hex) & 0xFF) as u8)
   |                     ^^^^^^^^^^^^^^^ attempt to shift right by `16_u8`, which would overflow
   |
   = note: `#[deny(arithmetic_overflow)]` on by default

error: aborting due to previous error; 3 warnings emitted

I have solved the issue by using u16's checked_shr(u16), however this makes my code more complex than I thought it would need to be, with:

let mut r: u8 = 0;
let mut g: u8 = 0;
let mut b: u8 = (hex as u8) & 0xFF;
if let Some(h16) = hex.checked_shr(16) {
    r = (h16 as u8) & 0xFF;
}
if let Some(h8) = hex.checked_shr(8) {
    g = (h8 as u8) & 0xFF;
}
Color::RGB(r, g, b)

I was wondering if there was a better way to solve the error, if I was just making a mistake in my original code, and/or if there is a better way of doing this? I was also trying to avoid turning off the #[deny(arithmetic_overflow)], but that could be a mistake. Thank you for your time!


Solution

  • The problem was solved by changing the hexadecimal value from u16 to u32, Thank you to matt and Mihir who pointed that out!