1. 비트 연산자란?
비트 연산(bitwise operation)은 한 개 혹은 두 개의 이진수에 대해 비트 단위로 적용되는 연산입니다
처음 비트 연산을 접하게 되면 "곱셈, 나눗셈을 사용하면 되지 이걸 왜 사용하나?"라는 의문이 들 수 있겠지만
비트연산은 곱셈, 나눗셈 연산자보다 실행속도가 빠르고 메모리 사용량이 적어 실무에서 자주 사용된다고 합니다.
그리고 이미지 및 영상처리에도 사용된다고 합니다.
2. 비트연산자(&, |, ^, ~)
- & (AND 연산자) - 피연산자의 양쪽 비트값이 모두 1이여야만 1을 결과로 얻는다. 그 외에는 0을 얻는다.
- | (OR 연산자)- 피연산자의 비트값 중 한쪽의 값만 1이여도 1을 결과로 얻는다. 모두 0일 경우 0을 얻는다.
- ^(XOR 연산자) - 피연산자의 비트값이 모두 다를 때만 1을 얻는다. 같을 경우 0을 얻는다.
- ~ (반전 연산자) - 피연산자의 비트 값을 0은 1로, 1은 0으로 바꾼다.
<example>
- & (AND 연산자)
System.out.println(a & b);
a | 0 | 1 | 1 | 0 | 1 | 1 | 0 | 0 | = 108 |
b | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 1 | = 85 |
결과 | 0 | 1 | 0 | 0 | 0 | 1 | 0 | 0 | = 68 |
AND 연산 활용1 :
화면을 좀 더 시원하게, 푸르스름하게 만들고싶다.
빨랑이나 초록을 약화(&)시키면 된다.
=> 다음과 같이 한 개의 점이 있다.
pixel = 10001100 10010010 10101100 (변경전 색)
pixel & 11011011 11011011 11111111 연산(빨강색과 초록색을 약화시키기)=> 10001000 10010000 10101100 (변경된 색)
AND 연산 활용2 :
System.out.println((57 & 0x1) == 0 ? "짝수" : "홀수");
- | (OR 연산자)
System.out.println(a | b);
a | 0 | 1 | 1 | 0 | 1 | 1 | 0 | 0 | = 108 |
b | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 1 | = 85 |
결과 | 0 | 1 | 1 | 1 | 1 | 1 | 0 | 1 | = 125 |
OR 연산 활용:
화면을 좀 더 엔틱하게 누렇게 표현하고 싶다.
=> 방법: 노란색 계통을 강화한다.
즉, 빨랑, 초록 빛을 강화하면 된다.
=> 다음과 같이 한 개의 점이 있다.
pixel = 10001100 10010010 10101100 (변경전 색)
a | 10010010 01001001 00000000 를 연산한다.
- ^(XOR 연산자)
System.out.println(a ^ b);
a | 0 | 1 | 1 | 0 | 1 | 1 | 0 | 0 | = 108 |
b | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 1 | = 85 |
결과 | 0 | 0 | 1 | 1 | 1 | 0 | 0 | 1 | = 57 |
- ~ (반전 연산자)
System.out.println(~a);
a | 0 | 0 | 0 | 1 | 1 | 0 | 0 | 1 |
결과 | 1 | 1 | 1 | 0 | 0 | 1 | 1 | 0 |
2. 쉬프트 연산자(<<, >>, >>>)
- x << y - 정수 x의 각 비트값을 y 만큼 왼쪽으로 이동시킨다(빈자리는 0으로 채워짐)
- x >> y - 정수 x의 각 비트값을 y 만큼 오른쪽으로 이동시킨다(빈자리 최상위 부호비트와 같은값으로 채워짐)
- x >>> y - 정수 x의 각 비트값을 y 만큼 왼쪽으로 이동시킨다(빈자리는 0으로 채워짐)
2-1
00001000(10진수로 8)을 기준으로 한다.
0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 |
8 << 1
0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 |
8 >> 1
0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 |
8 >>> 1
0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 |
2-2
11111000(10진수로 -8)을 기준으로 한다.
1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 |
-8 << 2
1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 |
-8 >> 2
1 | 1 | 1 | 1 | 1 | 1 | 1 | 0 |
-8 >>> 2
0 | 0 | 1 | 1 | 1 | 1 | 1 | 0 |
정리
- x >> n: 2의 n제곱을 주어진 양수(x)에 곱해준 값과 같다.
- 음수의 경우 양수로 바뀔수 있다...(주의)
- x << n: x를 2의 n제곱으로 나눈값과 같다
- 소수점이 있는 경우 그 수 보다 작은 바로 밑 정수 값이 된다.
3. 응용
'Java > 기초' 카테고리의 다른 글
[Java] JVM메모리와 메서드 호출 (1) | 2023.11.30 |
---|---|
[Java] Enum(열거형) (1) | 2023.11.02 |
[Java] Iterable 인터페이스와 Iterator (0) | 2023.11.01 |
[Java] Network Programming(네트워크 프로그래밍) (0) | 2023.11.01 |
[Java] JavaIO - (4) Object IO Stream(+깊은복사, 얕은복사) (0) | 2023.10.27 |