[C++] Bitwise operator (&, |, ^, ~, <<, >>)

JAsmine_log·2024년 2월 19일

Bitwise operator (비트 연산자)

비트 연산자는 변수(variable)의 값을 비트 패턴에 따라 수정 또는 변화시킴
* asm : Assembly Language

operatorasm equivalentdescription
&ANDBitwise AND
|ORBitwise inclusive OR
^XORBitwise exclusive OR
~NOTUnary complement (bit inversion)
<<SHLShift bits left
>>SHRShift bits right

* 간단히, ^(XOR)은 같으면 0, 다르면 1. 이 특성은 알고리즘 문제에 자주 활용됨

비트연산 예시

  • 코드(code) :
    * int : 4bytes
#include <iostream>
using namespace std;

int main() { 

  int x=0;  				// binary : 0
  int y=1; 					// binary : 1
  int result = 0;
  
  result = x&y;				// binary : 0 & 1
  cout << result << endl;
  
  result = x|y;				// binary : 0 | 1
  cout << result << endl;
  
  result = x^y;				// binary : 0 ^ 1
  cout << result << endl;
  
  result = ~x;				// binary : ~0
  cout << result << endl;
  
  result = x<<y;			// binary : 0 << 1
  cout << result << endl;
  
  result = x>>y;			// binary : 0 >> 1
  cout << result << endl;

  return 0;
}
>>0
1
1
-1
0
0

Reference

[1] https://cplusplus.com/doc/tutorial/operators/
[2] https://levelup.gitconnected.com/single-number-algorithm-7384f74422

profile
Everyday Research & Development

0개의 댓글