비트연산자
Integer.toBinaryString() 2진수
Integer.toOctalString() 8진수
Integer.toHexString() 16진수
정수형 숫자를 2진 코드로 바꿔주는 메소드로 8진수, 16진수로 변환하는 메소드도 존재한다. 비트 연산자의 종류는 아래와 같다.
연산 기호 |
내용 |
& |
AND 연산, 교집합 |
| |
OR 연산, 합집합 |
^ |
XOR 연산, 비트가 서로 다를 때 |
~ |
NOT 연산, 0과 1을 바꿈 |
<< >> |
SHIFT 연산, 자리 옮김 |
AND 연산
| public class Solution { |
| public static void main(String[] args) { |
| int A = 10; |
| int B = 15; |
| |
| System.out.println("A의 2진수: " + Integer.toBinaryString(A)); |
| System.out.println("B의 2진수: " + Integer.toBinaryString(B)); |
| System.out.println("AND 연산: " + Integer.toBinaryString(A & B)); |
| } |
| } |
| |
| A의 2진수: 1010 |
| B의 2진수: 1111 |
| AND 연산: 1010 |
OR 연산
| public class Solution { |
| public static void main(String[] args) { |
| int A = 10; |
| int B = 15; |
| |
| System.out.println("A의 2진수: " + Integer.toBinaryString(A)); |
| System.out.println("B의 2진수: " + Integer.toBinaryString(B)); |
| System.out.println("OR 연산: " + Integer.toBinaryString(A | B)); |
| } |
| } |
| |
| A의 2진수: 1010 |
| B의 2진수: 1111 |
| OR 연산: 1111 |
XOR 연산
| public class Solution { |
| public static void main(String[] args) { |
| int A = 10; |
| int B = 15; |
| |
| System.out.println("A의 2진수: " + Integer.toBinaryString(A)); |
| System.out.println("B의 2진수: " + Integer.toBinaryString(B)); |
| System.out.println("XOR 연산: " + Integer.toBinaryString(A ^ B)); |
| } |
| } |
| |
| A의 2진수: 1010 |
| B의 2진수: 1111 |
| XOR 연산: 101 |
NOT 연산
| public class Solution { |
| public static void main(String[] args) { |
| int A = 10; |
| int B = 15; |
| |
| System.out.println("A의 2진수: " + Integer.toBinaryString(A)); |
| System.out.println("B의 2진수: " + Integer.toBinaryString(B)); |
| System.out.println("NOT 연산: " + Integer.toBinaryString(~A)); |
| System.out.println("NOT 연산: " + Integer.toBinaryString(~B)); |
| } |
| } |
| |
| A의 2진수: 1010 |
| B의 2진수: 1111 |
| NOT 연산: 11111111111111111111111111110101 |
| NOT 연산: 11111111111111111111111111110000 |
SHIFT 연산
| public class Solution { |
| public static void main(String[] args) { |
| int A = 10; |
| int B = 15; |
| |
| System.out.println("A의 2진수: " + Integer.toBinaryString(A)); |
| System.out.println("B의 2진수: " + Integer.toBinaryString(B)); |
| System.out.println("SHIFT 연산: " + Integer.toBinaryString(A >> B)); |
| System.out.println("SHIFT 연산: " + Integer.toBinaryString(A << B)); |
| } |
| } |
| |
| A의 2진수: 1010 |
| B의 2진수: 1111 |
| SHIFT 연산: 0 |
| SHIFT 연산: 1010000000000000000 |