π™ΉπšŠπšŸπšŠ

[Java] 10μ§„μˆ˜ ↔ 2, 8, 16μ§„μˆ˜ λ³€ν™˜

ν•΄λ²„λ‹ˆ 2023. 11. 19. 09:04
λ°˜μ‘ν˜•

 

 

ν”„λ‘œκ·Έλž˜λ¨ΈμŠ€ λ‹€μŒ 큰 숫자 문제λ₯Ό ν’€λ˜ 쀑 μ§„μˆ˜ λ³€ν™˜ν•˜λŠ” 것에 λŒ€ν•΄μ„œ μ°Ύμ•„λ³΄κ²Œ 됐닀. 

 

 

10μ§„μˆ˜λ₯Ό 2, 8, 16μ§„μˆ˜λ‘œ λ³€ν™˜ν•˜λŠ” 방법

int decimal = 17;

String binary = Integer.toBinaryString(decimal); // 10μ§„μˆ˜ → 2μ§„μˆ˜
String octal = Integer.toOctalString(decimal); // 10μ§„μˆ˜ → 8μ§„μˆ˜
String hexaDecimal = Integer.toHexString(decimal); // 10μ§„μˆ˜ → 16μ§„μˆ˜

 

 

 

10μ§„μˆ˜λ₯Ό 2μ§„μˆ˜λ‘œ λ°”κΎΈκ³  μ‹Άλ‹€λ©΄

Integer.toBinaryString(decimal);

 

μ΄λ ‡κ²Œ μ“΄λ‹€.

λ°˜ν™˜ κ°’ ν˜•μ‹μ€ String이닀. 

 

 

 

 

 

 

 

 

 

 

 

2, 8, 16μ§„μˆ˜λ₯Ό 10μ§„μˆ˜λ‘œ λ³€ν™˜ν•˜κΈ° 

int binary2 = Integer.parseInt(binary, 2);
int octal2 = Integer.parseInt(octal, 8);
int hexaDecimal2 = Integer.parseInt(hexaDecimal, 16);

 

 

 

 

Integer.parseInt(binary, 2);

 

첫 번째 인자 : λ°”κΎΈκ³ μž ν•˜λŠ” 숫자 λ„£κΈ° 

두 번째 인자 : 첫 번째 μΈμžκ°€ λͺ‡ μ§„μˆ˜μΈμ§€ λ„£κΈ° 

 

 

 

 

첫 번째 μΈμžλŠ” String만 넣을 수 μžˆλ‹€. (μˆ«μžλŠ” 넣을 수 μ—†λ‹€.)

 

 

 

 

 

 

 

2μ§„μˆ˜λ₯Ό 10μ§„μˆ˜λ‘œ λ³€ν™˜ν•˜λŠ” μ½”λ“œ 

        int num16 = Integer.parseInt("10111", 2); 
        int num17 = Integer.parseInt("1010101", 2);

        bw.write(String.valueOf(num16) + "\n"); 	// 23
        bw.write(String.valueOf(num17));		// 85

 

 

 

 

 

 

 

 

총 μ½”λ“œ 

package algorithm;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));

        int decimal = 17;

        String binary = Integer.toBinaryString(decimal); // 10μ§„μˆ˜ → 2μ§„μˆ˜
        String octal = Integer.toOctalString(decimal); // 10μ§„μˆ˜ → 8μ§„μˆ˜
        String hexaDecimal = Integer.toHexString(decimal); // 10μ§„μˆ˜ → 16μ§„μˆ˜

        bw.write("10μ§„μˆ˜ :" + String.valueOf(decimal) + "\n");
        bw.write("2μ§„μˆ˜ :" + binary + "\n");
        bw.write("8μ§„μˆ˜ :" + octal + "\n");
        bw.write("16μ§„μˆ˜ :" + hexaDecimal + "\n");


        int binary2 = Integer.parseInt(binary, 2);
        int octal2 = Integer.parseInt(octal, 8);
        int hexaDecimal2 = Integer.parseInt(hexaDecimal, 16);

        bw.write("λ‹€μ‹œ 10μ§„μˆ˜λ‘œ : " + binary2 + "\n");
        bw.write("λ‹€μ‹œ 10μ§„μˆ˜λ‘œ : " + octal2 + "\n");
        bw.write("λ‹€μ‹œ 10μ§„μˆ˜λ‘œ : " + hexaDecimal2 + "\n");

        bw.flush();
        bw.close();
    }
}

 

λ°˜μ‘ν˜•