[英]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)
我想知道是否有更好的方法来解决错误,如果我只是在原始代码中犯了错误,和/或是否有更好的方法来做到这一点? 我还试图避免关闭#[deny(arithmetic_overflow)]
,但这可能是一个错误。 感谢您的时间!
通过将十六进制值从 u16 更改为 u32 解决了问题,感谢 matt 和 Mihir 指出这一点!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.