
1. 십진수를 이진수로 바꾸기
십진수를 이진수로 바꾸는 방법부터 정리한다.
십진수를 2 미만이 될때까지 2로 계속 나누고, 나눌때마다 발생하는 나머지를 이진수로 저장하는 원리이다.
위의 문장만으로 벌써 반복문 조건이 완성된다.
1 2 3 4 5 6 7
| int[] binaries = new int[32]; int = 0; while(integer>=2) { binaries[i] = integer%2; integer/=2; i++; }
|
그리고 이를 StringBuilder에 저장하는데, 이진수 값을 저장한 배열은 우리가 생각한 이진수의 반대로 저장되었으므로 StringBuilder 타입에 담을때엔 iterator를 거꾸로 돌리면 된다.
1 2 3 4
| StringBuffer result = new StringBuffer(""); for(int j=i; j>=0; j--) { result.append(binaries[j]); }
|
완성된 코드는 아래와 같다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| public class NumericChange { public static void main(String[] args) { System.out.println(IntegerToBinary(16)); } static int IntegerToBinary(int integer) { int[] binaries = new int[32]; while(integer>=2) { binaries[i] = integer%2; integer/=2; i++; } binaries[i] = integer; StringBuffer result = new StringBuffer(""); for(int j=i; j>=0; j--) { result.append(binaries[j]); } return Integer.parseInt(String.valueOf(result)); } }
|
사실 십진수를 이진수로 바꾸는 방법은 Integer
클래스의 메소드를 이용해서 간단히 할 수 있다.
1
| Integer.toBinaryString(integer);
|
그런데 이 메소드는 반환 타입이 String이므로, 정수형으로 파싱을 해주어야 한다.
1
| Integer.parseInt(Integer.toBinaryString(integer));
|
2. 이진수를 십진수로 바꾸기
이진수를 십진수로 바꾸는 원리를 알아보자.

이진수의 자릿수에서 1이 있는 인덱스마다 2의 지수2의 지수만큼을 합산하면 된다.
위의 원리대로 풀어가려면 일단 정수형 타입으로 가져오는 이진수를 자릿수마다 분리해서 배열로 담아야 한다.
1 2
| String temp = String.valueOf(binary); String[] splitted = temp.split("");
|
일단 문자열 타입의 배열에 담아둔다.
그리고 반복문을 돌려서 배열의 값이 "1"
이면, 그에 해당하는 인덱스를 지수로 갖는 2를 더하면 된다. 이 때 역시 우리의 의도대로 인덱스를 가져오려면 배열을 거꾸로 돌려야 하며, iterator를 하나 더 사용해야 한다.
1 2 3 4 5 6 7 8
| int result = 0; int j = 0; for (int i = splitted.length-1; i >= 0; i--) { if(splitted[i].equals("1")) { result+=Math.pow(2, j); } j++; }
|
완성된 코드는 다음과 같다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| public class NumericChange { public static void main(String[] args) { System.out.println(IntegerToBinary(16)); } public static int BinaryToInteger(int binary) { String temp = String.valueOf(binary); String[] splitted = temp.split(""); int result = 0; int j = 0; for (int i = splitted.length-1; i >= 0; i--) { if(splitted[i].equals("1")) { result+=Math.pow(2, j); } j++; } return result; } }
|