铁锈溢出左移
Rust overflowing shift left
我试图将 4 个字节组合成一个 u32,编译器告诉我移位已经溢出。
这是我的代码:
pub fn get_instruction(file: &[u8], counter: usize) {
let ins = u32::from(file[counter] << 24)
| u32::from(file[counter + 1] << 16)
| u32::from(file[counter + 2] << 8)
| u32::from(file[counter + 3]);
println!("{:x}", ins);
}
您获得了操作员优先级并且投错了:
pub fn get_instruction(file: &[u8], counter: usize) {
let ins = u32::from(file[counter]) << 24
| u32::from(file[counter + 1]) << 16
| u32::from(file[counter + 2]) << 8
| u32::from(file[counter + 3]);
println!("{:x}", ins);
}
您在 尝试移动 u8
24 位后进行转换,这是您的问题。
没有必要自己摆弄这些位——您可以使用函数 u32::from_be_bytes()
代替:
pub fn get_instruction(file: &[u8], counter: usize) {
let ins_bytes = <[u8; 4]>::try_from(&file[counter..counter + 4]).unwrap();
let ins = u32::from_be_bytes(ins_bytes);
println!("{:x}", ins);
}
我试图将 4 个字节组合成一个 u32,编译器告诉我移位已经溢出。 这是我的代码:
pub fn get_instruction(file: &[u8], counter: usize) {
let ins = u32::from(file[counter] << 24)
| u32::from(file[counter + 1] << 16)
| u32::from(file[counter + 2] << 8)
| u32::from(file[counter + 3]);
println!("{:x}", ins);
}
您获得了操作员优先级并且投错了:
pub fn get_instruction(file: &[u8], counter: usize) {
let ins = u32::from(file[counter]) << 24
| u32::from(file[counter + 1]) << 16
| u32::from(file[counter + 2]) << 8
| u32::from(file[counter + 3]);
println!("{:x}", ins);
}
您在 尝试移动 u8
24 位后进行转换,这是您的问题。
没有必要自己摆弄这些位——您可以使用函数 u32::from_be_bytes()
代替:
pub fn get_instruction(file: &[u8], counter: usize) {
let ins_bytes = <[u8; 4]>::try_from(&file[counter..counter + 4]).unwrap();
let ins = u32::from_be_bytes(ins_bytes);
println!("{:x}", ins);
}