fork(1) download
  1. #include <bitset>
  2. #include <iostream>
  3. #include <string>
  4. #include <utility>
  5. using namespace std;
  6.  
  7. template<unsigned N> class BitArray : public bitset<N> {
  8. public:
  9. typedef typename bitset<N>::reference reference;
  10. bool operator[](unsigned i) const { return bitset<N>::operator[](i-1); }
  11. reference operator[](unsigned i) { return bitset<N>::operator[](i-1); }
  12. BitArray() : bitset<N>() { }
  13. explicit BitArray(string const& s) : bitset<N>(string(s.rbegin(), s.rend())) { }
  14. string to_string() const {
  15. string s = bitset<N>::to_string();
  16. return string(s.rbegin(), s.rend());
  17. }
  18. friend ostream& operator<<(ostream& os, BitArray const& a) {
  19. os << a.to_string();
  20. return os;
  21. }
  22. };
  23.  
  24. template<unsigned N>
  25. pair< BitArray<N/2>, BitArray<N/2> > split(BitArray<N> const& a) {
  26. pair< BitArray<N/2>, BitArray<N/2> > p;
  27. for (unsigned i = 1; i <= N/2; ++i) {
  28. p.first[i] = a[i];
  29. }
  30. for (unsigned i = 1; i <= N/2; ++i) {
  31. p.second[i] = a[N/2+i];
  32. }
  33. return p;
  34. }
  35.  
  36. //------------------------------------------------------------------------------
  37.  
  38. unsigned const N = 8;
  39.  
  40. BitArray<N> encode(BitArray<N> const& A) {
  41.  
  42. // Split the input into two halves.
  43. pair< BitArray<N/2>, BitArray<N/2> > const& halves = split(A);
  44. BitArray<N/2> const& A1 = halves.first;
  45. BitArray<N/2> const& A2 = halves.second;
  46.  
  47. // Initialize the result with all bits to zero.
  48. BitArray<N> B;
  49.  
  50. // Do the work.
  51. for (unsigned i = 1; i <= N/2; ++i) {
  52. for (unsigned j = 1; j <= N/2; ++j) {
  53. B[i+j] = B[i+j] ^ (A1[i] & A2[j]);
  54. }
  55. }
  56.  
  57. return B;
  58. }
  59.  
  60. //------------------------------------------------------------------------------
  61.  
  62. void test(string const& s) {
  63. cout << s << " -> " << encode(BitArray<N>(s)) << endl;
  64. }
  65.  
  66. int main() {
  67. string s1, s2;
  68. s1 = "00000000";
  69. test(s1);
  70. cout << endl;
  71. s1 = "11111111";
  72. test(s1);
  73. cout << endl;
  74. s1 = "00001111";
  75. s2 = "11110000";
  76. test(s1);
  77. test(s2);
  78. cout << endl;
  79. s1 = "01101101";
  80. s2 = "11010110";
  81. test(s1);
  82. test(s2);
  83. cout << endl;
  84. s1 = "10001111";
  85. s2 = "11111000";
  86. test(s1);
  87. test(s2);
  88. s1 = "11001010";
  89. s2 = "10101100";
  90. test(s1);
  91. test(s2);
  92. return 0;
  93. }
Success #stdin #stdout 0s 3476KB
stdin
Standard input is empty
stdout
00000000 -> 00000000

11111111 -> 01010101

00001111 -> 00000000
11110000 -> 00000000

01101101 -> 00101110
11010110 -> 00101110

10001111 -> 01111000
11111000 -> 01111000
11001010 -> 01111000
10101100 -> 01111000