1 module dcrypt.util.bitmanip;
2 
3 alias rotateLeft rol;
4 alias rotateRight ror;
5 
6 /// rot shift to the left
7 /// Params:
8 /// x = integer to shift
9 /// shiftAmount = number of bits to shift
10 @safe
11 @nogc
12 T rotateLeft(T)(T x, uint shiftAmount) pure nothrow 
13 {
14 	enum nbits = T.sizeof*8;
15 	//shiftAmount %= nbits;
16 	return cast(T)(x << shiftAmount) | (x >>> (nbits-shiftAmount));
17 }
18 
19 /// test rotateLeft
20 unittest {
21 	ubyte b0 = 0b10000001;
22 	ubyte b1 = 0b00000011;
23 	ubyte b2 = 0b00000110;
24 	ubyte b7 = 0b11000000;
25 	
26 	assert(rotateLeft(b0,0) == b0);
27 	assert(rotateLeft(b0,1) == b1);
28 	assert(rotateLeft(b0,2) == b2);
29 	assert(rotateLeft(b0,7) == b7);
30 	assert(rotateLeft(b0,8) == b0);
31 }
32 
33 /// rot shift to the right
34 /// Params:
35 /// x = integer to shift
36 /// shiftAmount = number of bits to shift
37 @safe
38 @nogc
39 T rotateRight(T)(T x, uint shiftAmount) pure nothrow
40 {
41 	enum nbits = T.sizeof*8;
42 	//shiftAmount %= nbits;
43 	return cast(T)((x >>> shiftAmount) | (x << (nbits-shiftAmount)));
44 }
45 
46 /// test rotateRight
47 unittest {
48 	ubyte b0 = 0b00000101;
49 	ubyte b1 = 0b10000010;
50 	ubyte b2 = 0b01000001;
51 	ubyte b7 = 0b00001010;
52 	
53 	assert(rotateRight(b0,0) == b0);
54 	assert(rotateRight(b0,1) == b1);
55 	assert(rotateRight(b0,2) == b2);
56 	assert(rotateRight(b0,7) == b7);
57 	assert(rotateRight(b0,8) == b0);
58 }