Rust Tutorial

Rust - right shift assignment operator



The Bitwise right shift assignment operator (>>=) assigns the first operand a value equal to the result of Bitwise right shift operation of two operands.

(x >>= y) is equivalent to (x = x >> y)

The Bitwise right shift operator (>>) takes the two numbers and right shift the bits of first operand by number of place specified by second operand. For example: for right shifting the bits of x by y places, the expression (x>>y) can be used. It is equivalent to dividing x by 2y.

The example below describes how right shift operator works:

1000 >> 2 returns 250

                      (In Binary)
   1000         ->    1111101000  
   >> 2                     |  right shift the bits
   -----                    V  by 2 places
    250         <-      11111010 
                      (In Binary) 

The code of using right shift operator (>>) is given below:

fn main() {
  let mut x = 1000;

  //right shift assignment operation
  x >>= 2;

  //Displaying the result
  println!("x = {}", x);
}

The output of the above code will be:

x = 250

Example: Find largest power of 2 less than or equal to given number

Consider an integer 1000. In the bit-wise format, it can be written as 1111101000. However, all bits are not written here. A complete representation will be 32 bit representation as given below:

00000000000000000000001111101000  

Performing n = n | (n>>i) operation, where i = 1, 2, 4, 8, 16 will change all right side bit to 1. When applied on 1000, the result in 32 bit representation is given below:

00000000000000000000001111111111 

Adding one to this result and then right shifting the result by one place will give largest power of 2 less than or equal to 1000.

00000000000000000000001000000000 

The below code will calculate the largest power of 2 less than or equal to given number.

fn max_power_of_two(n: i32) -> i32{
  let mut n = n;
  //changing all right side bits to 1.
  n = n | (n>>1);
  n = n | (n>>2);
  n = n | (n>>4);
  n = n | (n>>8);
  n = n | (n>>16);
  
  //adding 1 to n makes smallest power
  //of 2 greater than given number
  n = n + 1;

  //right shift by one position makes
  //largest power of 2 less than or 
  //equal to given number
  n >>= 1;
  
  return n;
}

fn main() {
  println!("max_power_of_two(100) = {}", max_power_of_two(100));
  println!("max_power_of_two(500) =  {}", max_power_of_two(500));
  println!("max_power_of_two(1000) = {}", max_power_of_two(1000));   
}

The above code will give the following output:

max_power_of_two(100) = 64
max_power_of_two(500) = 256
max_power_of_two(1000) = 512

❮ Rust - Operators

5