-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbit_rotate.c
33 lines (21 loc) · 978 Bytes
/
bit_rotate.c
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
#include "bit_rotate.h"
// return the value bits rotated left n_rotations
uint16_t bit_rotate(int n_rotations, uint16_t bits) {
int actual_rotations = n_rotations % 16;
if (actual_rotations == 0) return bits;
uint16_t initial_mask = 0xFFFF;
if (actual_rotations > 0) {
uint16_t overflow_mask = (initial_mask << (16 - actual_rotations));
uint16_t overflow = (overflow_mask & bits) >> (16 - actual_rotations);
uint16_t mask = (initial_mask >> actual_rotations);
uint16_t rotated = (bits & mask) << actual_rotations;
return (rotated | overflow);
} else {
actual_rotations *= -1;
uint16_t overflow_mask = (initial_mask >> (16 - actual_rotations));
uint16_t overflow = (overflow_mask & bits) << (16 - actual_rotations);
uint16_t mask = (initial_mask << actual_rotations);
uint16_t rotated = (bits & mask) >> actual_rotations;
return (rotated | overflow);
}
}