O.1 Bit flags and bit manipulation via std::bitset

주홍영·2022년 3월 12일
0

Learncpp.com

목록 보기
56/199

https://www.learncpp.com/cpp-tutorial/o-1-bit-flags-and-bit-manipulation-via-stdbitset/

이번 챕터에서는 bit 연산에 관해서 집중적으로 살펴보낟
optional 챕터이기는 하나 bit 연산을 통한 문제해결 또한
유용하므로 짚고 넘어간다

#include < bitset >
std::bitset 을 이용해 bit manipulation을 할 수 있다
예시는 다음과 같다

#include <bitset>
#include <iostream>

int main()
{
    std::bitset<8> bits{ 0b0000'0101 }; // we need 8 bits, start with bit pattern 0000 0101
    bits.set(3); // set bit position 3 to 1 (now we have 0000 1101)
    bits.flip(4); // flip bit 4 (now we have 0001 1101)
    bits.reset(4); // set bit 4 back to 0 (now we have 0000 1101)

    std::cout << "All the bits: " << bits << '\n';
    std::cout << "Bit 3 has value: " << bits.test(3) << '\n';
    std::cout << "Bit 4 has value: " << bits.test(4) << '\n';

    return 0;
}
profile
청룡동거주민

0개의 댓글