안녕하십니까. 김동우입니다.
이번 노트에서는 비트와이즈 연산자에 대해 얘기할까 합니다.
그럼 코드부터 보시겠습니다.
#include <iostream>
#include <bitset> // binary library
using namespace std;
int main()
{
// Bitwise operator
// << left shift - default
// >> right shift
// cout-cin 에서의 부등호는 의미가 아예 다르다.
// operator overloading -> bitwise operator는 아니다.
// ~, &, |, ^ 차례대로 NOT, AND, OR, XOR
// 1. shift operator
unsigned int a = 3;
cout << '\n' << std::bitset<8>(a) << endl;
// output : 00000011
unsigned int b = a << 4;
cout << std::bitset<8>(b) << " " << b << endl;
// output : 00110000 48
// left shift
cout << '\n' << std::bitset<8>(a << 1) << " " << (a << 1) << endl;
cout << std::bitset<8>(a << 2) << " " << (a << 2) << endl;
cout << std::bitset<8>(a << 3) << " " << (a << 3) << endl;
cout << std::bitset<8>(a << 4) << " " << (a << 4) << endl;
// (output)
// 00000110 6
// 00001100 12
// 00011000 24
// 00110000 48
// 보다시피 2의 거듭제곱을 a에 곱해주고 있다.
// 즉, shift 연산을 잘 활용하면 특정 unsigned값에 대해 2의 제곱수를
// pow() 없이 빠르고 쉬운 연산을 할 수 있다.
// right shift
int c(1024);
cout << '\n' << std::bitset<12>(c) << " " << c << endl;
// output : 010000000000 1024
cout << '\n'<< std::bitset<12>(c >> 1) << " " << (c >> 1) << endl;
cout << std::bitset<12>(c >> 2) << " " << (c >> 2) << endl;
cout << std::bitset<12>(c >> 3) << " " << (c >> 3) << endl;
cout << std::bitset<12>(c >> 4) << " " << (c >> 4) << endl;
// (output)
// 001000000000 512
// 000100000000 256
// 000010000000 128
// 000001000000 64
// 반대로 2의 거듭제곱으로 나눈다.
unsigned int x(0b1100);
unsigned int y(0b0110);
cout << '\n' << x << " " << y << endl; // output : 12 6
cout << '\n' << std::bitset<4>( x & y ) << endl; // x &= y;
cout << std::bitset<4>( x | y ) << endl; // x |= y;
cout << std::bitset<4>( x ^ y ) << endl; // x ^= y;
// (output)
// 0100 -> bitwise AND
// 1110 -> bitwise OR
// 1010 -> bitwise XOR
return 0;
}
#include <iostream>
#include <bitset>
using namespace std;
int main()
{
// Quiz
// 0110 << 2 -> decimal
// 0001 1000 = 24 or 0110 = 6, (<< 2) == (*4), 6 * 4 = 24
// 0110 >> 2 -> decimal
// 0001 = 1
// 5 | 12
// 0101 | 1100 = 1101
// 5 & 12
// 0101 & 1100 = 0100
// 5 ^ 12
// 0101 ^ 1100 = 1001
// 정답
unsigned int x(0b0110);
int y(5);
int z(12);
cout << '\n'<< ( x << 2 ) << endl;
cout << ( x >> 2 ) << endl;
cout << '\n'<< std::bitset<4>(y & z) << endl; // y &= z;
cout << std::bitset<4>(y | z) << endl; // y |= z;
cout << std::bitset<4>(y ^ z) << endl; // y ^= z;
// 24 1
// 0100
// 1101
// 1001
return 0;
}
그럼 이번 글은 이만 마치도록 하겠습니다. 감사합니다.