Bitwise Operations

Understanding bitwise operations is crucial, especially in low-level programming where manipulation of individual bits is common. Rust provides a set of bitwise operators that allow for precise control over binary data. Let's explore each of these operators with examples:

1. Binary Notation:

let value = 0b11110101; // Binary notation

2. Visual Chunking with Underscores:

let value = 0b1111_0101; // Visual chunking for readability

3. Displaying Binary Representation:

let value: u8 = 0b1111_0101;
// or
//let value = 0b1111_0101u8;
println!("Decimal: {}", value);
println!("Binary: {:08b}", value); // Display binary representation

4. Bitwise NOT Operator:

let mut value: u8 = 0b1111_0101;
value = !value; // Bitwise NOT operator
println!("NOT Result: {:08b}", value); // NOT Result: 00001010

5. Bitwise AND Operator:

let mut value: u8 = 0b1111_0101;
let mask: u8 = 0b1111_1011;
value &= mask; // Bitwise AND operator
println!("AND Result: {:08b}", value); // AND Result: 11110001

6. Bitwise OR Operator:

let mut value: u8 = 0b1111_0101;
let mask: u8 = 0b0000_1000;
value |= mask; // Bitwise OR operator
println!("OR Result: {:08b}", value); // OR Result: 11111101

7. Bitwise XOR Operator:

let mut value: u8 = 0b1111_0101;
let mask: u8 = 0b1010_1010;
value ^= mask; // Bitwise XOR operator
println!("XOR Result: {:08b}", value); // XOR Result: 01011111

8. Bitwise Left Shift Operator:

let mut value: u8 = 0b0000_1010;
value <<= 2; // Bitwise left shift operator
println!("Left Shift Result: {:08b}", value); // Left Shift Result: 00101000

9. Bitwise Right Shift Operator:

let mut value: u8 = 0b0000_1010;
value >>= 2; // Bitwise right shift operator
println!("Right Shift Result: {:08b}", value); // Right Shift Result: 00000010

These examples demonstrate how bitwise operators can be used to manipulate binary data efficiently in Rust. Understanding these operations is essential for tasks such as configuring hardware registers or implementing custom data structures at a low level.

Comments

Popular posts from this blog

Deploy FastAPI on AWS Lambda: A Step-by-Step Guide