Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <fstream>
- #include <iostream>
- #include <vector>
- #include <numeric>
- #include <algorithm>
- #define D 3
- #define K (1 << D) /* K = 2^D */
- #define MASK (K - 1) /* MASK = K - 1 */
- struct windows {
- struct window {
- int one;
- int length;
- } window[sizeof(unsigned long) * CHAR_BIT];
- int length;
- };
- int get_msb(unsigned long a)
- {
- int n = 0;
- while (a > 0) {
- a >>= 1;
- n++;
- }
- return n;
- }
- void decompose_bits(unsigned long n, struct windows* windows)
- {
- int one, j;
- int i = get_msb(n) - 1;
- windows->length = 0;
- while (i >= 0) {
- one = (n >> i) & 1;
- for (j = 1; j < D && i >= j && one == ((n >> (i - j)) & 1); j++) {
- }
- windows->window[windows->length].one = one;
- windows->window[windows->length].length = j;
- windows->length++;
- i -= j;
- }
- }
- unsigned long sliding_window(unsigned long a, unsigned long n)
- {
- unsigned long x = 1, aa = a * a;
- int i, j;
- unsigned long table[D + 1];
- struct windows windows;
- table[0] = a;
- for (i = 1; i < D + 1; i++) {
- table[i] = aa * table[i - 1];
- }
- decompose_bits(n, &windows);
- for (i = 0; i < windows.length; i++) {
- for (j = 0; j < windows.window[i].length; j++) {
- x *= x;
- }
- if (windows.window[i].one) {
- j = (1 << (windows.window[i].length - 1)) - 1;
- x *= table[j];
- }
- }
- return x;
- }
- int main()
- {
- int num[] = { 1,0,1,0,1,1,0,1,1, 1, 0, 1 , 1 };
- std::vector<int> v, calc;
- // 配列を逆順にコピー
- std::reverse_copy(std::begin(num), std::end(num), std::back_inserter(v));
- // 配列の要素数を取得
- int max_size = (int)v.size();
- for (int i = 0; i < max_size; i++) {
- // 2のiのべき乗を計算
- calc.push_back(num[i] * sliding_window(2, i));
- }
- // 合計を計算
- int sum = std::reduce(calc.begin(), calc.end());
- // 結果を表示
- std::cout << "2進数の\t0b";
- for (auto e : v) {
- std::cout << e;
- }
- std::cout << "\tは10進数に直すと";
- std::cout << sum << "です" << std::endl;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement