fork download
  1. #include <iostream>
  2. #include <stdint.h>
  3. #include <array>
  4.  
  5. namespace details
  6. {
  7. constexpr uint8_t bit( unsigned byte, unsigned n ) {
  8. return (byte>>n)&1;
  9. }
  10. constexpr uint8_t even_bits(uint8_t byte) {
  11. return bit(byte, 0) | (bit(byte, 2)<<1) | (bit(byte, 4)<<2) | (bit(byte, 6)<<3);
  12. }
  13. constexpr uint8_t odd_bits(uint8_t byte) {
  14. return even_bits(byte/2);
  15. }
  16. template<unsigned...>struct indexes{using type=indexes;};
  17. template<unsigned Max,unsigned...Is>struct make_indexes:make_indexes<Max-1,Max-1,Is...>{};
  18. template<unsigned...Is>struct make_indexes<0,Is...>:indexes<Is...>{};
  19. template<unsigned Max>using make_indexes_t=typename make_indexes<Max>::type;
  20.  
  21. template<unsigned...Is>
  22. constexpr std::array< uint8_t, 256 > even_bit_table( indexes<Is...> ) {
  23. return {
  24. even_bits(Is)...
  25. };
  26. }
  27. template<unsigned...Is>
  28. constexpr std::array< uint8_t, 256 > odd_bit_table( indexes<Is...> ) {
  29. return {
  30. odd_bits(Is)...
  31. };
  32. }
  33. constexpr std::array< uint8_t, 256 > even_bit_table() {
  34. return even_bit_table( make_indexes_t<256>{} );
  35. }
  36. constexpr std::array< uint8_t, 256 > odd_bit_table() {
  37. return odd_bit_table( make_indexes_t<256>{} );
  38. }
  39.  
  40. static constexpr auto etable = even_bit_table();
  41. static constexpr auto otable = odd_bit_table();
  42. }
  43.  
  44. uint8_t constexpr even_bits( uint16_t in ) {
  45. return details::etable[(uint8_t)in] | ((details::etable[(uint8_t)(in>>8)])<<4);
  46. }
  47. uint8_t constexpr odd_bits( uint16_t in ) {
  48. return details::otable[(uint8_t)in] | ((details::otable[(uint8_t)(in>>8)])<<4);
  49. }
  50. template<class A>
  51. void print_array( A&& a ) {
  52. std::size_t cnt = 0;
  53. std::cout << "[ ";
  54. for (auto&& e:a) {
  55. if (cnt!=0)
  56. std::cout << ", ";
  57. std::cout << (int)e;
  58. ++cnt;
  59. if (!(cnt%8))
  60. std::cout << "\n ";
  61. }
  62. std::cout << "]\n";
  63. }
  64. void dump( uint16_t x )
  65. {
  66. std::cout << (int)odd_bits(x) << "\n";
  67. std::cout << (int)odd_bits(x<<1) << "\n";
  68. std::cout << (int)odd_bits(x<<2) << "\n";
  69. std::cout << (int)odd_bits(x<<3) << "\n";
  70. std::cout << (int)odd_bits(x<<4) << "\n";
  71. std::cout << (int)odd_bits(x<<5) << "\n";
  72. std::cout << (int)odd_bits(x<<6) << "\n";
  73. std::cout << (int)odd_bits(x<<7) << "\n";
  74. }
  75. int main() {
  76. // print_array(otable);
  77. // print_array(etable);
  78. dump(1);
  79. dump(1<<8);
  80. // your code goes here
  81. return 0;
  82. }
Success #stdin #stdout 0.01s 3344KB
stdin
Standard input is empty
stdout
0
1
0
2
0
4
0
8
0
16
0
32
0
64
0
128