libcruft-util/bitwise.hpp

71 lines
1.7 KiB
C++
Raw Normal View History

/*
2015-04-13 18:05:28 +10:00
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
2015-04-13 18:05:28 +10:00
* http://www.apache.org/licenses/LICENSE-2.0
*
2015-04-13 18:05:28 +10:00
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
2012-04-23 13:06:41 +10:00
* Copyright 2011 Danny Robson <danny@nerdcruft.net>
*/
#ifndef __UTIL_BITWISE_HPP
#define __UTIL_BITWISE_HPP
#include <cstdint>
2012-01-04 17:06:57 +11:00
#include "debug.hpp"
const uint8_t BITMASK_1BITS = 0x01;
const uint8_t BITMASK_2BITS = 0x03;
const uint8_t BITMASK_3BITS = 0x07;
const uint8_t BITMASK_4BITS = 0x0F;
const uint8_t BITMASK_5BITS = 0x1F;
const uint8_t BITMASK_6BITS = 0x3F;
const uint8_t BITMASK_7BITS = 0x7F;
const uint8_t BITMASK_8BITS = 0xFF;
2014-04-16 19:15:54 +10:00
#define MODT(x) ((x) % (sizeof (T) * 8))
2012-01-04 17:06:57 +11:00
template <typename T>
2014-04-16 19:15:54 +10:00
constexpr T
rotatel (const T &value, size_t magnitude) {
2014-04-16 19:15:54 +10:00
return (value << MODT (magnitude)) |
(value >> sizeof (value) * 8 - MODT (magnitude));
2012-01-04 17:06:57 +11:00
}
2014-04-16 19:15:54 +10:00
template <typename T>
constexpr T
rotater (const T &value, size_t magnitude) {
return (value >> MODT (magnitude)) |
(value << sizeof (value) * 8 - MODT (magnitude));
}
#undef MODT
2014-07-15 19:49:29 +10:00
// TODO: make constexpr for C++14
template <typename T>
T
reverse (T value) {
T out = value;
size_t bits = sizeof (value) * 8 - 1;
for (value >>= 1; value; value >>= 1) {
out <<= 1;
out |= value & 0x01;
--bits;
}
out <<= bits;
return out;
}
2015-04-13 18:06:08 +10:00
#endif