Advertisement
Naohiro19

2進数を10進数に変換

Feb 6th, 2022
1,229
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.23 KB | None | 0 0
  1.  
  2. #include <fstream>
  3. #include <iostream>
  4. #include <vector>
  5. #include <numeric>
  6. #include <algorithm>
  7.  
  8. #define D 3
  9. #define K (1 << D) /* K = 2^D */
  10. #define MASK (K - 1) /* MASK = K - 1 */
  11.  
  12.  
  13. struct windows {
  14.     struct window {
  15.         int one;
  16.         int length;
  17.     } window[sizeof(unsigned long) * CHAR_BIT];
  18.     int length;
  19. };
  20.  
  21. int get_msb(unsigned long a)
  22. {
  23.     int n = 0;
  24.  
  25.     while (a > 0) {
  26.         a >>= 1;
  27.         n++;
  28.     }
  29.  
  30.     return n;
  31. }
  32.  
  33. void decompose_bits(unsigned long n, struct windows* windows)
  34. {
  35.     int one, j;
  36.     int i = get_msb(n) - 1;
  37.  
  38.     windows->length = 0;
  39.  
  40.     while (i >= 0) {
  41.         one = (n >> i) & 1;
  42.  
  43.         for (j = 1; j < D && i >= j && one == ((n >> (i - j)) & 1); j++) {
  44.         }
  45.  
  46.         windows->window[windows->length].one = one;
  47.         windows->window[windows->length].length = j;
  48.         windows->length++;
  49.         i -= j;
  50.     }
  51. }
  52.  
  53. unsigned long sliding_window(unsigned long a, unsigned long n)
  54. {
  55.     unsigned long x = 1, aa = a * a;
  56.     int i, j;
  57.     unsigned long table[D + 1];
  58.     struct windows windows;
  59.  
  60.     table[0] = a;
  61.  
  62.     for (i = 1; i < D + 1; i++) {
  63.         table[i] = aa * table[i - 1];
  64.     }
  65.  
  66.     decompose_bits(n, &windows);
  67.  
  68.     for (i = 0; i < windows.length; i++) {
  69.         for (j = 0; j < windows.window[i].length; j++) {
  70.             x *= x;
  71.         }
  72.  
  73.         if (windows.window[i].one) {
  74.             j = (1 << (windows.window[i].length - 1)) - 1;
  75.             x *= table[j];
  76.         }
  77.     }
  78.  
  79.     return x;
  80. }
  81.  
  82. int main()
  83. {
  84.     int num[] = { 1,0,1,0,1,1,0,1,1, 1, 0, 1 , 1 };
  85.     std::vector<int> v, calc;
  86.  
  87.     // 配列を逆順にコピー
  88.     std::reverse_copy(std::begin(num), std::end(num), std::back_inserter(v));
  89.  
  90.     // 配列の要素数を取得
  91.     int max_size = (int)v.size();
  92.  
  93.     for (int i = 0; i < max_size; i++) {
  94.         // 2のiのべき乗を計算
  95.         calc.push_back(num[i] * sliding_window(2, i));
  96.     }
  97.    
  98.     // 合計を計算
  99.     int sum = std::reduce(calc.begin(), calc.end());
  100.  
  101.     // 結果を表示
  102.     std::cout << "2進数の\t0b";
  103.     for (auto e : v) {
  104.         std::cout << e;
  105.     }
  106.     std::cout << "\tは10進数に直すと";
  107.     std::cout << sum << "です" << std::endl;
  108. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement