프로그래밍을 하다 보면 숫자를 한 진법에서 다른 진법으로 변환해야 하는 경우가 자주 발생합니다. 예를 들어 8진수(Octal)로 표현된 값을 2진수(Binary), 10진수(Decimal), 16진수(Hexadecimal) 등으로 바꿔야 할 때가 그렇습니다. 다행히 Java에서는 Integer 클래스가 제공하는 메서드만 활용하면 별도의 변환 로직을 직접 구현하지 않고도 간단하게 처리할 수 있습니다.
핵심 원리
Java의 Integer.parseInt(String num, int source) 메서드는 문자열 형태의 숫자를 지정된 진법(source)의 정수로 해석하고, Integer.toString(int value, int destination) 메서드는 해당 정수를 목표 진법(destination)의 문자열로 변환해 줍니다. 이 두 메서드를 조합하면 어떤 진법이든 다른 진법으로 손쉽게 변환할 수 있습니다.
예제 코드
public class Demo{
public static String base_convert(String num, int source, int destination){
return Integer.toString(Integer.parseInt(num, source), destination);
}
public static void main(String[] args){
String my_num = "345";
int source = 8;
int destination = 2;
System.out.println("8진수를 2진수로 변환: " + base_convert(my_num, source, destination));
destination = 10;
System.out.println("8진수를 10진수로 변환: " + base_convert(my_num, source, destination));
destination = 16;
System.out.println("8진수를 16진수로 변환: " + base_convert(my_num, source, destination));
}
}실행 결과
8진수를 2진수로 변환: 11100101 8진수를 10진수로 변환: 229 8진수를 16진수로 변환: e5
코드 설명
Demo라는 이름의 클래스 안에는 base_convert라는 정적(static) 메서드가 정의되어 있습니다. 이 메서드는 세 개의 매개변수를 받습니다. 첫 번째는 변환 대상 숫자 문자열(num), 두 번째는 원본 진법(source), 세 번째는 목표 진법(destination)입니다.
메서드 내부에서는 먼저 Integer.parseInt(num, source)를 통해 입력 문자열을 원본 진법 기준의 정수로 파싱한 뒤, Integer.toString(..., destination)으로 목표 진법의 문자열로 변환하여 반환합니다.
main 메서드에서는 변환할 숫자("345")와 원본 진법(8진수)을 설정하고, 목표 진법을 2, 10, 16으로 차례대로 변경하면서 base_convert 함수를 호출합니다. 각 호출 결과는 콘솔에 출력됩니다.
정리
이처럼 Integer.parseInt()와 Integer.toString() 두 메서드만 조합하면 2진수부터 36진수까지 어떤 진법 간의 변환이든 단 몇 줄의 코드로 처리할 수 있습니다. 진법 변환 로직을 직접 작성하는 것보다 코드가 훨씬 간결해지고 오류 가능성도 줄어들기 때문에, 실무에서도 널리 사용되는 패턴입니다.