Add bitrotate module.
[gnulib.git] / lib / bitrotate.h
1 /* bitrotate.h - Rotate bits in integers
2    Copyright (C) 2008 Free Software Foundation, Inc.
3
4    This program is free software: you can redistribute it and/or modify
5    it under the terms of the GNU General Public License as published by
6    the Free Software Foundation; either version 3 of the License, or
7    (at your option) any later version.
8
9    This program is distributed in the hope that it will be useful,
10    but WITHOUT ANY WARRANTY; without even the implied warranty of
11    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12    GNU General Public License for more details.
13
14    You should have received a copy of the GNU General Public License
15    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
16
17 /* Written by Simon Josefsson <simon@josefsson.org>, 2008. */
18
19 #ifndef _GL_BITROTATE_H
20 #define _GL_BITROTATE_H
21
22 #include <stdint.h>
23
24 /* Given an unsigned 32-bit argument X, return the value corresponding
25    to rotating the bits N steps to the left.  N must be between 1 and
26    31 inclusive. */
27 static inline uint32_t
28 rotl32 (uint32_t x, int n)
29 {
30   return ((x << n) | (x >> (32 - n))) & 0xFFFFFFFF;
31 }
32
33 /* Given an unsigned 32-bit argument X, return the value corresponding
34    to rotating the bits N steps to the right.  N must be between 1 to
35    31 inclusive.*/
36 static inline uint32_t
37 rotr32 (uint32_t x, int n)
38 {
39   return ((x >> n) | (x << (32 - n))) & 0xFFFFFFFF;
40 }
41
42 /* Given an unsigned 16-bit argument X, return the value corresponding
43    to rotating the bits N steps to the left.  N must be between 1 to
44    15 inclusive. */
45 static inline uint16_t
46 rotl16 (uint16_t x, int n)
47 {
48   return ((x << n) | (x >> (16 - n))) & 0xFFFFFFFF;
49 }
50
51 /* Given an unsigned 16-bit argument X, return the value corresponding
52    to rotating the bits N steps to the right.  N must be in 1 to 15
53    inclusive. */
54 static inline uint16_t
55 rotr16 (uint16_t x, int n)
56 {
57   return ((x >> n) | (x << (16 - n))) & 0xFFFFFFFF;
58 }
59
60 #endif /* _GL_BITROTATE_H */