공log/[JAVA]
[JAVA] 자바 #2 - 진법 변환하기
ming_OoO
2023. 9. 4. 14:33
728x90
1. 10진수를 2진법, 8진법, 16진법으로 변환하기
java.lang.Integer 클래스의 메서드를 이용하여 10진수를 2진수, 8진수, 16진수로 변환할 수 있다.
리턴 타입은 모두 동일하게 String형으로 반환된다.
toBinaryString(int i) : 10진수 -> 2진수
toOctalString(int i) : 10진수 -> 8진수
toHexaString(int i) : 10진수 -> 16진수
public class NumberConvert {
public static void main(String[] args) {
int decimal = 10;
String binary = Integer.toBinaryString(decimal); // 10진수 -> 2진수
String octal = Integer.toOctalString(decimal); // 10진수 -> 8진수
String hexaDecimal = Integer.toHexString(decimal); // 10진수 -> 16진수
System.out.println("10진수 : " + decimal);
System.out.println("2진수 : " + binary);
System.out.println("8진수 : " + octal);
System.out.println("16진수 : " + hexaDecimal);
}
}
결과
10진수 : 10
2진수 : 1010
8진수 : 12
16진수 : a
2. 2진법, 8진법, 16진법을 10진수로 변환하기
java.lang.Integer 클래스의 parseInt() 메서드를 이용하여 2진수, 8진수, 16진수를 10진수로 변환할 수 있다.
리턴 타입은 모두 동일하게 int형으로 반환된다.
일반적으로 자주 사용하는 parseInt(String s)는 문자열(s)을 10진수로 읽어서 int로 반환한다. 하지만 진법 변환을 위해서는 아래와 같이 parseInt(String s, int radix)를 사용한다.
parseInt(String s, int radix) : 문자열(s)을 변환할 진수(radix)로 읽어서 int로 반환
public class NumberConvert {
public static void main(String[] args) {
int binaryToDecimal = Integer.parseInt("1010", 2);
int octalToDecimal = Integer.parseInt("12", 8);
int hexaToDecimal = Integer.parseInt("A", 16);
System.out.println("2진수(1010) -> 10진수 : " + binaryToDecimal); // 10
System.out.println("8진수(12) -> 10진수 : " + octalToDecimal); // 10
System.out.println("16진수(a) -> 10진수 : " + hexaToDecimal); // 10
}
}
결과
2진수(1010) -> 10진수 : 10
8진수(12) -> 10진수 : 10
16진수(a) -> 10진수 : 10
728x90