Created
December 30, 2015 08:31
-
-
Save cho45/f3d5775b56d9f6e2c22a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <cstdio> | |
#include <stdint.h> | |
#include <iostream> | |
template <class T, class U> | |
void is(T got, U expected) { | |
if (got == expected) { | |
std::cout << "ok" << std::endl; | |
} else { | |
std::cout << "not ok " << got << " != " << expected << std::endl; | |
} | |
} | |
template <class T, uint8_t s, uint8_t e = s> | |
struct bits { | |
T ref; | |
static constexpr T mask = (T)(~( (T)(~0) << (e - s + 1))) << s; | |
void operator=(const T val) { ref = (ref & ~mask) | ((val & (mask >> s)) << s); } | |
operator T() const { return (ref & mask) >> s; } | |
}; | |
template <uint8_t s, uint8_t e = s> | |
using bits8 = bits<uint8_t, s, e>; | |
int main () { | |
union { | |
uint8_t raw = 0; | |
bits8<0, 1> FAULT_QUEUE ; | |
bits8<2> CT_PIN_POLARITY ; | |
bits8<3> INT_PIN_POLARITY ; | |
bits8<4> INT_CT_MODE ; | |
bits8<5, 6> OPERATION_MODE ; | |
bits8<7> RESOLUTION ; | |
} config; | |
config.OPERATION_MODE = 0b11; | |
is((uint)config.raw, 0b01100000); | |
config.FAULT_QUEUE = 0b10; | |
is((uint)config.raw, 0b01100010); | |
config.RESOLUTION = 1; | |
is((uint)config.raw, 0b11100010); | |
config.OPERATION_MODE = 0; | |
is((uint)config.raw, 0b10000010); | |
config.raw = 0; | |
is((uint)config.OPERATION_MODE, 0b00); | |
config.raw = 0b01000000; | |
is((uint)config.OPERATION_MODE, 0b10); | |
config.FAULT_QUEUE = 0b111; | |
is((uint)config.raw, 0b01000011); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment