Skip to content

Std::bitset

Syntax

std::bitset<5> B;

템플릿 인자로 Bit의 개수를 입력하면 된다. 크기는 Compile time에 정해져야 한다. Run time에 결정하고 싶을 경우 Dynamic bitset을 사용하면 된다.

Dynamic bitset

Boost에 포함되어 있다.

Methods

bool bitset<N>::any()
어떤 값이라도 true일 경우 true, 아니라면 false.
bool bitset<N>::test(i)
i번째 값을 반환.
bitset<N>&bitset<N>::set(i,b)
i번째 값을 b로 설정한다. b는 적어주지 않으면 default 가 1이다.
bitset<N>&bitset<N>::reset(i)
i번째 값을 0으로 설정한다.
size_t bitset<N>::count()
1의 갯수를 return 한다.

Example

#include <iostream>
#include <bitset>
using namespace std;

int main() {
    unsigned short short1 = 4;    
    bitset<16> bitset1{short1};   // the bitset representation of 4
    cout << bitset1 << endl;  // 0000000000000100

    unsigned short short2 = short1 << 1;     // 4 left-shifted by 1 = 8
    bitset<16> bitset2{short2};
    cout << bitset2 << endl;  // 0000000000001000

    unsigned short short3 = short1 << 2;     // 4 left-shifted by 2 = 16
    bitset<16> bitset3{short3};
    cout << bitset3 << endl;  // 0000000000010000
}

Favorite site