Comment detail

2進数の記述 (Nested Flatten)

C++ でやるのはちょっと前に話題になってましたね。 でそれを参考にテンプレート特殊化とプリプロセッサマクロを使ったやつを。

8進数リテラルを使うので桁数に限界があります。unsigned long long が 64bits の環境で22桁ほど。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>

template<unsigned long long n, int base = 8>
struct binary {
    enum {
        value = (binary<n / base>::value << 1) + (n % base == 1 ? 1 : 0)
    };
};

template<>
struct binary<0> {
    enum {
        value = 0
    };
};

#define BIN(n) binary<0 ## n ## ul>::value

int main()
{
    std::cout << BIN(1101001) << std::endl; // => 105
    std::cout << BIN(1111111111111111111111) << std::endl; // => 4194303
    return 0;
}

Index

Feed

Other

Link

Pathtraq

loading...