bitops: setter and add const

Signed-off-by: Rick Altherr <kc8apf@kc8apf.net>
Signed-off-by: Tim 'mithro' Ansell <mithro@mithis.com>
This commit is contained in:
Rick Altherr 2017-12-04 11:02:55 -08:00 committed by Tim 'mithro' Ansell
parent 6a4402415e
commit 9f1e936ab0
2 changed files with 40 additions and 3 deletions

View File

@ -41,3 +41,31 @@ TEST(BitFieldGetTest, SelectMidway) {
uint32_t expected = prjxray::bit_field_get(0xFFCCBBAA, 18, 8);
EXPECT_EQ(static_cast<uint32_t>(0x4BB), expected);
}
TEST(BitFieldSetTest, WriteOneBit) {
uint32_t actual = prjxray::bit_field_set(
static_cast<uint32_t>(0x0), 23, 23,
static_cast<uint32_t>(0x1));
EXPECT_EQ(actual, static_cast<uint32_t>(0x800000));
}
TEST(BitFieldSetTest, WriteOneBitWithOutOfRangeValue) {
uint32_t actual = prjxray::bit_field_set(
static_cast<uint32_t>(0x0), 23, 23,
static_cast<uint32_t>(0x3));
EXPECT_EQ(actual, static_cast<uint32_t>(0x800000));
}
TEST(BitFieldSetTest, WriteMultipleBits) {
uint32_t actual = prjxray::bit_field_set(
static_cast<uint32_t>(0x0), 18, 8,
static_cast<uint32_t>(0x123));
EXPECT_EQ(actual, static_cast<uint32_t>(0x12300));
}
TEST(BitFieldSetTest, WriteMultipleBitsWithOutOfRangeValue) {
uint32_t actual = prjxray::bit_field_set(
static_cast<uint32_t>(0x0), 18, 8,
static_cast<uint32_t>(0x1234));
EXPECT_EQ(actual, static_cast<uint32_t>(0x23400));
}

View File

@ -4,7 +4,7 @@
namespace prjxray {
template<typename UInt>
constexpr UInt bit_mask(int bit) {
constexpr UInt bit_mask(const int bit) {
return (static_cast<UInt>(1) << bit);
}
@ -19,7 +19,7 @@ constexpr UInt bit_all_ones() {
}
template<typename UInt>
constexpr UInt bit_mask_range(int top_bit, int bottom_bit) {
constexpr UInt bit_mask_range(const int top_bit, const int bottom_bit) {
return ((bit_all_ones<UInt>() >> (bit_sizeof<UInt>() - 1 - top_bit)) &
(bit_all_ones<UInt>() - bit_mask<UInt>(bottom_bit) +
static_cast<UInt>(1)));
@ -27,10 +27,19 @@ constexpr UInt bit_mask_range(int top_bit, int bottom_bit) {
template<typename UInt>
constexpr UInt bit_field_get(UInt value, int top_bit, int bottom_bit) {
constexpr UInt bit_field_get(UInt value, const int top_bit, const int bottom_bit) {
return (value & bit_mask_range<UInt>(top_bit, bottom_bit)) >> bottom_bit;
}
template<typename UInt>
constexpr UInt bit_field_set(const UInt reg_value,
const int top_bit, const int bottom_bit,
const UInt field_value) {
return ((reg_value & ~bit_mask_range<UInt>(top_bit, bottom_bit)) |
((static_cast<UInt>(field_value) << bottom_bit) &
bit_mask_range<UInt>(top_bit, bottom_bit)));
}
} // namespace prjxray
#endif // PRJXRAY_LIB_BIT_OPS_H