你如何在 Rust 中设置、清除和切换单个位? [英] How do you set, clear and toggle a single bit in Rust?
问题描述
如何在 Rust 中设置、清除和切换一点?
How do I set, clear and toggle a bit in Rust?
推荐答案
与许多其他语言一样,按位运算符 &
(按位与)、|
(按位或), ^
(按位异或) 存在:
Like many other languages, the bitwise operators &
(bitwise AND), |
(bitwise OR), ^
(bitwise XOR) exist:
fn main() {
let mut byte: u8 = 0b0000_0000;
byte |= 0b0000_1000; // Set a bit
println!("0b{:08b}", byte);
byte &= 0b1111_0111; // Unset a bit
println!("0b{:08b}", byte);
byte ^= 0b0000_1000; // Toggle a bit
println!("0b{:08b}", byte);
}
与其他语言的主要区别在于按位非,它使用 !
而不是 ~
:
The main difference from other languages is in bitwise NOT, which uses !
instead of ~
:
fn main() {
let mut byte: u8 = 0b0000_0000;
byte = !byte; // Flip all bits
println!("0b{:08b}", byte);
}
您还可以向左或向右移动位:
You can also shift bits left or right:
fn main() {
let mut byte: u8 = 0b0000_1000;
byte <<= 1; // shift left one bit
println!("0b{:08b}", byte);
byte >>= 1; // shift right one bit
println!("0b{:08b}", byte);
}
还有许多其他概念性的东西最终会进行位级操作,而这些操作并没有用运算符来表达.查看整数文档以获取示例.一个有趣的例子是 leading_zeros
.以下是如何旋转一定数量的位:
There are many other conceptual things that ultimately do bit-level manipulation that are not expressed with operators. Check out the documentation for an integer for examples. One interesting example is leading_zeros
. Here is how to rotate by a certain number of bits:
fn main() {
let mut byte: u8 = 0b1000_0000;
byte = byte.rotate_left(1); // rotate left one bit
println!("0b{:08b}", byte);
byte = byte.rotate_right(1); // rotate right one bit
println!("0b{:08b}", byte);
}
这篇关于你如何在 Rust 中设置、清除和切换单个位?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!