JAVA
[JAVA] - 진법 변환 정리
by nam_ji
2024. 2. 18.
진법 변환 정리
10진법과 2진법
- 우리가 일상생활에서 사용하는 것은 10진법입니다. (0 ~ 9까지 표현한 것)
- 1946년에 개발된 컴퓨터 에니악(ENIAC)은 사람에게 익숙한 10진법이었으나, 전기회로는 불안정하여 전압을 10단계로 나누어 처리하기엔 한계가 있었습니다.
그래서 1950년에 개발된 에드박(EDVAC)은 전기가 흐르면 1, 안 흐르면 0만으로 동작하도록 설계했습니다.
- 컴퓨터는 모든 값을 2진수로 바꾸어 저장됩니다.
-
2진수 |
10진수 |
0 |
0 |
1 |
1 |
10 |
2 |
11 |
3 |
100 |
4 |
101 |
5 |
110 |
6 |
111 |
7 |
1000 |
8 |
1001 |
9 |
1010 |
10 |
비트(bit)와 바이트(byte)
- 한 자리의 2진수를 비트(bit, binary digit)라고 하며, 1비트는 컴퓨터가 값을 저장할 수 있는 최소 단위입니다. 하지만 비트는 너무 작은 단위이기에, 1비트를 8개 묶은 바이트라는 단위로 정의해서 데이터의 기본단위로 사용합니다.
8진법과 16진법
- 2진법은 0,1만 표기하기 때문에, 값을 표현할 때 자릿수가 상당히 길어진다는 단점이 존재합니다.
이러한 단점 보완을 위해 8진법과 16진법도 많이 사용됩니다.
-
2진수 |
8진수 |
10진수 |
16진수 |
0 |
0 |
0 |
0 |
1 |
1 |
1 |
1 |
10 |
2 |
2 |
2 |
11 |
3 |
3 |
3 |
100 |
4 |
4 |
4 |
101 |
5 |
5 |
5 |
110 |
6 |
6 |
6 |
111 |
7 |
7 |
7 |
1000 |
10 |
8 |
8 |
1001 |
11 |
9 |
9 |
1010 |
12 |
10 |
A |
1011 |
13 |
11 |
B |
1100 |
14 |
12 |
C |
1110 |
16 |
14 |
E |
1111 |
17 |
15 |
F |
10000 |
20 |
16 |
10 |
정수의 진법 변환
public class NumberConversion {
public static void main(String[] args) {
// 테스트를 위한 10진수 값 = 25
int a = 25;
System.out.println("10진수 -> 2진수");
System.out.println(Integer.toBinaryString(a));
System.out.println(Integer.toString(a,2));
System.out.println("10진수 -> 3진수");
System.out.println(Integer.toString(a,3));
System.out.println("10진수 -> 4진수");
System.out.println(Integer.toString(a,4));
System.out.println("10진수 -> 5진수");
System.out.println(Integer.toString(a,5));
System.out.println("10진수 -> 6진수");
System.out.println(Integer.toString(a,6));
System.out.println("10진수 -> 7진수");
System.out.println(Integer.toString(a,7));
System.out.println("10진수 -> 8진수");
System.out.println(Integer.toOctalString(a));
System.out.println(Integer.toString(a,8));
System.out.println("10진수 -> 16진수");
System.out.println(Integer.toString(a,16));
System.out.println(Integer.toHexString(a));
System.out.println("================================================");
// 테스트를 위한 n진수 값 = 25
String b = "11001"; // <- 25
System.out.println("2진수 -> 10진수");
System.out.println(Integer.parseInt(b,2));
System.out.println("3진수 -> 10진수");
System.out.println(Integer.parseInt(b,3));
System.out.println("4진수 -> 10진수");
System.out.println(Integer.parseInt(b,4));
System.out.println("5진수 -> 10진수");
System.out.println(Integer.parseInt(b,5));
System.out.println("6진수 -> 10진수");
System.out.println(Integer.parseInt(b,6));
System.out.println("7진수 -> 10진수");
System.out.println(Integer.parseInt(b,7));
System.out.println("8진수 -> 10진수");
System.out.println(Integer.parseInt(b,8));
System.out.println("16진수 -> 10진수");;
System.out.println(Integer.parseInt(b,16));
}
}
// ==========출력========== //
10진수 -> 2진수
11001
11001
10진수 -> 3진수
221
10진수 -> 4진수
121
10진수 -> 5진수
100
10진수 -> 6진수
41
10진수 -> 7진수
34
10진수 -> 8진수
31
31
10진수 -> 16진수
19
19
================================================
2진수 -> 10진수
25
3진수 -> 10진수
109
4진수 -> 10진수
321
5진수 -> 10진수
751
6진수 -> 10진수
1513
7진수 -> 10진수
2745
8진수 -> 10진수
4609
16진수 -> 10진수
69633