Rust 按位运算
Rust bitwise operations
我目前正在尝试将 rust 中的十六进制值(作为 u16)转换为存储为单独变量的 RGB 值,所有类型均为 u8。我决定这样做的方法是使用按位运算符使用以下代码从十六进制中获取单独的值:
Color::RGB(((hex >> (16u8)) & 0xFF) as u8, ((hex >> (8u8)) & 0xFF) as u8, ((hex) & 0xFF) as u8)
导致错误:
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
我已经使用 u16 的 checked_shr(u16)
解决了这个问题,但是这使我的代码比我想象的更复杂,其中:
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)
我想知道是否有更好的方法来解决这个错误,如果我只是在我的原始代码中犯了一个错误,and/or是否有更好的方法来解决这个问题?我也试图避免关闭 #[deny(arithmetic_overflow)]
,但这可能是一个错误。感谢您的宝贵时间!
通过将十六进制值从 u16 更改为 u32 解决了问题,感谢 matt 和 Mihir 指出了这一点!
我目前正在尝试将 rust 中的十六进制值(作为 u16)转换为存储为单独变量的 RGB 值,所有类型均为 u8。我决定这样做的方法是使用按位运算符使用以下代码从十六进制中获取单独的值:
Color::RGB(((hex >> (16u8)) & 0xFF) as u8, ((hex >> (8u8)) & 0xFF) as u8, ((hex) & 0xFF) as u8)
导致错误:
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
我已经使用 u16 的 checked_shr(u16)
解决了这个问题,但是这使我的代码比我想象的更复杂,其中:
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)
我想知道是否有更好的方法来解决这个错误,如果我只是在我的原始代码中犯了一个错误,and/or是否有更好的方法来解决这个问题?我也试图避免关闭 #[deny(arithmetic_overflow)]
,但这可能是一个错误。感谢您的宝贵时间!
通过将十六进制值从 u16 更改为 u32 解决了问题,感谢 matt 和 Mihir 指出了这一点!