Bit Count
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <bits/stdc++.h> | |
using namespace std; | |
int main() { | |
// 4 bit | |
for (int i = 0; i < (1 << 4); i++) { | |
// convert to 8 bit | |
cout << i << "(" << bitset<8>(i) << ")"; | |
// count bits | |
cout << ": " << __builtin_popcount(i) << " bits." << endl; | |
} | |
return 0; | |
} | |
/* | |
0(00000000): 0 bits. | |
1(00000001): 1 bits. | |
2(00000010): 1 bits. | |
3(00000011): 2 bits. | |
4(00000100): 1 bits. | |
5(00000101): 2 bits. | |
6(00000110): 2 bits. | |
7(00000111): 3 bits. | |
8(00001000): 1 bits. | |
9(00001001): 2 bits. | |
10(00001010): 2 bits. | |
11(00001011): 3 bits. | |
12(00001100): 2 bits. | |
13(00001101): 3 bits. | |
14(00001110): 3 bits. | |
15(00001111): 4 bits. | |
*/ |
bitset
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <bitset> | |
int main() | |
{ | |
// 整数から8ビットのビット集合を構築 | |
std::bitset<8> bs1(131uL); // 10000011 | |
// 文字列から8ビットのビット集合を構築 | |
std::bitset<8> bs2("10000011"); | |
// 1ビット目が1かを判定 | |
if (bs1[1]) { | |
std::cout << "1st bit is 1" << std::endl; | |
} | |
// 2ビット目を1にする | |
bs1.set(2); | |
std::cout << "2nd bit to 1 : " << bs1 << std::endl; | |
// 2ビット目を0に戻す | |
bs1.reset(2); | |
// いずれかのビットが1かを判定 | |
if (bs1.any()) { | |
std::cout << "some bits are 1" << std::endl; | |
} | |
// 論理演算 | |
std::bitset<8> and_bits = bs1 & std::bitset<8>("10000001"); // 論理積 | |
std::bitset<8> or_bits = bs1 | std::bitset<8>("00010100"); // 論理和 | |
std::bitset<8> xor_bits = bs1 ^ std::bitset<8>("00100011"); // 排他的論理和 | |
std::cout << "and : " << and_bits << std::endl; | |
std::cout << "or : " << or_bits << std::endl; | |
std::cout << "xor : " << xor_bits << std::endl; | |
} | |
/* | |
1st bit is 1 | |
2nd bit to 1 : 10000111 | |
some bits are 1 | |
and : 10000001 | |
or : 10010111 | |
xor : 10100000 | |
*/ |
No comments:
Post a Comment