Bitwise Operation 비트 연산

정현철·2023년 3월 17일
0

Basic

비트(Bit) 단위로 논리 연산을 할 때 사용하는 연산자.
할당된 비트 전체를 왼쪽 · 오른쪽으로 이동시키는 연산 역시 가능하다.

Bitwise Operation is an operator used to perform bit-level logical operation.
It is also possible to perform operations that shift the entire assigned bit to the left or right.

e.g.) a = 1010, b = 0100

OperatorNameExample
&ANDa & b = 0000
|ORa | b = 1110
^XORa ^ b = 1110
~NOT~a = 0101
<<Left Shifta << n == a * 2^n
>>Right Shifta >> n == a 2(-n)

Caution

  • 사칙연산은 비교, 논리 연산자보다 우선순위가 높다.

  • 반면 Shift 제외, 비트연산의 우선순위는 논리연산보다 높고, 비교연산보다 낮다.

  • Arithmetic operators have a higher priority than comparison and logical operators.

  • On the other hand, the priority of bitwise operators, excluding shift, is higher than the logical operators and lower than the comparison operators.

( +, -, *, / ) Arithmetic operators
> ( ==, >=, < ) comparison operators
> ( &, | , ^ ) bitwise operators
> ( &&, || ) logical operators


// wrong.
if (x & y == 0)  // == if (x & (y == 0))

// right.
if ((x & y) == 0)


Application

1. &(AND), |(OR)

  • 비트 집합 두 가지를 AND 하면 교집합, OR 하면 합집합을 구할 수 있다.

0개의 댓글

Powered by GraphCDN, the GraphQL CDN