fork(1) download
  1. #include <cstdint>
  2. #include <iostream>
  3. #include <string>
  4.  
  5. template<uint8_t Bit>
  6. struct set {
  7. static_assert(Bit < 8);
  8. static constexpr uint8_t bit = Bit;
  9. static constexpr bool isNeg = false;
  10. };
  11.  
  12. template<uint8_t Bit>
  13. struct unset {
  14. static_assert(Bit < 8);
  15. static constexpr uint8_t bit = Bit;
  16. static constexpr bool isNeg = true;
  17. };
  18.  
  19. template<typename bit, typename... bits>
  20. constexpr uint8_t gen_mask(uint8_t value, uint8_t last_result) {
  21. uint8_t result = 0;
  22. if(bit::isNeg ^ ((value & (1 << bit::bit)) == 0)) {
  23. result = last_result | (1 << bit::bit);
  24. } else {
  25. result = last_result & ~(1 << bit::bit);
  26. }
  27. if constexpr(sizeof...(bits) == 0) {
  28. return result;
  29. } else {
  30. return gen_mask<bits...>(value, result);
  31. }
  32. }
  33.  
  34. template<typename... bits>
  35. constexpr uint8_t gen_mask(uint8_t value) { return gen_mask<bits...>(value, 0); }
  36.  
  37.  
  38. int main() {
  39. uint8_t value = 0b00001111;
  40. uint8_t mask = gen_mask<set<3>, set<5>, set<6>, unset<0>, unset<7>>(value);
  41. uint8_t result = value ^ mask;
  42. std::cout << std::to_string(value) << std::endl;
  43. std::cout << std::to_string(mask) << std::endl;
  44. std::cout << std::to_string(result) << std::endl;
  45. }
Success #stdin #stdout 0s 4544KB
stdin
Standard input is empty
stdout
15
97
110