Rust bitwise operator
Created By: chatGPT
In Rust, bitwise operators are used to perform bit-level operations on integer types. These operators allow manipulation of the binary representation of numbers. The common bitwise operators in Rust include AND, OR, XOR, NOT, and shift operators.
// Bitwise operators in Rust
fn main() {
let a: u32 = 0b0101; // 5 in binary
let b: u32 = 0b0011; // 3 in binary
let and_result = a & b; // AND
let or_result = a | b; // OR
let xor_result = a ^ b; // XOR
let not_result = !a; // NOT
let left_shift = a << 1; // Left Shift
let right_shift = a >> 1; // Right Shift
println!("AND Result: {:b}", and_result);
println!("OR Result: {:b}", or_result);
println!("XOR Result: {:b}", xor_result);
println!("NOT Result: {:b}", not_result);
println!("Left Shift Result: {:b}", left_shift);
println!("Right Shift Result: {:b}", right_shift);
}
The AND operator (
&
) compares each bit of two numbers; it returns a new number where each bit is set to 1 if both bits are 1. Similarly, the OR operator (|
) returns a new number where each bit is set to 1 if at least one of the bits is 1. The XOR operator (^
) returns a new number where each bit is set to 1 if the bits differ.// Demonstrating AND, OR, and XOR
fn demonstrate_bitwise() {
let a: u8 = 15; // 00001111
let b: u8 = 9; // 00001001
let and_result = a & b; // 00001001 -> 9
let or_result = a | b; // 00001111 -> 15
let xor_result = a ^ b; // 00000110 -> 6
println!("AND: {}", and_result);
println!("OR: {}", or_result);
println!("XOR: {}", xor_result);
}
The NOT operator (
!
) inverts all bits of a number. For example, if a number is 00001111
, applying NOT results in 11110000
. The shift operators allow moving bits left or right, effectively multiplying or dividing the number by two for each shift.// Demonstrating NOT and Shift Operators
fn demonstrate_not_and_shift() {
let a: u8 = 5; // 00000101
let not_result = !a; // Inverts to 11111010
let left_shift = a << 1; // Moves left (10 in decimal)
let right_shift = a >> 1; // Moves right (2 in decimal)
println!("NOT Result: {}", not_result);
println!("Left Shift Result: {}", left_shift);
println!("Right Shift Result: {}", right_shift);
}