Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you set, clear and toggle a single bit in Rust?

How do I set, clear and toggle a bit in Rust?

like image 826
zzeroo Avatar asked Nov 07 '16 14:11

zzeroo


People also ask

How do I toggle a single bit?

The XOR operator ( ^ ) can be used to toggle a bit. number ^= 1UL << n; That will toggle the n th bit of number .

How do I turn off a particular bit in a number?

The idea is to use bitwise <<, & and ~ operators. Using expression “~(1 << (k – 1))“, we get a number which has all bits set, except the k'th bit. If we do bitwise & of this expression with n, we get a number which has all bits same as n except the k'th bit which is 0.

How do you set a ith bit to 0?

You just have to replace the logical OR with a logical AND operation. You would use the & operator for that: pt = pt & ~(1 << i); You have to invert your mask because logical AND ing with a 1 will maintain the bit while 0 will clear it... so you'd need to specify a 0 in the location that you want to clear.


1 Answers

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); } 

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); } 

The book has some more information

like image 118
Shepmaster Avatar answered Sep 28 '22 07:09

Shepmaster