-
Notifications
You must be signed in to change notification settings - Fork 1
/
8.rs
36 lines (31 loc) · 962 Bytes
/
8.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
/// A function that returns the value of the integer x rotated to the right by n
/// positions.
///
/// @param u32 x Number to have its bits rotated.
/// @param i32 n Amount of bits to be rotated.
///
/// @return u32 Number resultant from operation.
fn rightrot(x: u32, n: i32) -> u32
{
let mut n_bits = 0;
let mut k = x;
let rightmost_mask = !(!0 << n);
if x == 0 {
return 0;
}
while k > 0 {
k /= 2;
n_bits += 1;
}
return ((x & rightmost_mask) << (n_bits - (n % n_bits))) | (x >> n);
}
/// A program to test changing bits.
fn main()
{
print!("rightrot(255, 1)\t=>\t{}\n", rightrot(255, 1));
print!("rightrot(0, 4)\t\t=>\t{}\n", rightrot(0, 4));
print!("rightrot(85, 4)\t\t=>\t{}\n", rightrot(85, 4));
print!("rightrot(!0, 4)\t\t=>\t{}\n", rightrot(!0, 4));
print!("rightrot(!0, 31)\t=>\t{}\n", rightrot(!0, 31));
print!("rightrot(10, 3)\t\t=>\t{}\n", rightrot(10, 3));
}