POST

JAVA 16진수의 문자열을 2진수 문자열로 반환하자

16진수(Hexadecimal)의 문자열(String)을 2진수(Binary number) 문자열(String)로 반환하자


조건1 16진수(Hexadecimal)와 2진수(Binary number) 모두 문자열(String)이어야 한다.

조건 2 아래처럼 배열을 사용한다.

String[] hex2bin = {"0000","0001","0010","0011",

    "0100","0101","0110","0111",

    "1000","1001","1010","1011",

    "1100","1101","1110","1111"};


결과

16진수 문자열을 입력하세요.

1abc

"1abc"에 대한 이진수는 0001 1010 1011 1100 



소스 코드

public static void main(String[] args) {

Scanner input = new Scanner(System.in);

System.out.println("16진수 문자열을 입력하세요.");

ToBinary tobin = new ToBinary(input.next()); // 객체 생성

tobin.hexTobin(); // 메소드 호출

}


class ToBinary {

private String hex; // 16진 문자열 저장변수

private String[] hex2bin = {"0000","0001","0010","0011","0100","0101",

"0110","0111","1000","1001","1010","1011","1100","1101","1110","1111"}; // 2진수 문자열

public ToBinary(String s) {

hex=s;

}

public void hexTobin() {

System.out.print("\""+hex+"\"에 대한 이진수는 ");

for(int i=0;i<hex.length();i++){ // 문자열의 길이만큼 반복

switch(hex.charAt(i)) { // switch문 사용 하여 문자열의 문자 비교

case '0':

System.out.print(hex2bin[0]+" ");

break;

case '1':

System.out.print(hex2bin[1]+" ");

break;

case '2':

System.out.print(hex2bin[2]+" ");

break;

case '3':

System.out.print(hex2bin[3]+" ");

break;

case '4':

System.out.print(hex2bin[4]+" ");

break;

case '5':

System.out.print(hex2bin[5]+" ");

break;

case '6':

System.out.print(hex2bin[6]+" ");

break;

case '7':

System.out.print(hex2bin[7]+" ");

break;

case '8':

System.out.print(hex2bin[8]+" ");

break;

case '9':

System.out.print(hex2bin[9]+" ");

break;

case 'a':

System.out.print(hex2bin[10]+" ");

break;

case 'b':

System.out.print(hex2bin[11]+" ");

break;

case 'c':

System.out.print(hex2bin[12]+" ");

break;

case 'd':

System.out.print(hex2bin[13]+" ");

break;

case 'e':

System.out.print(hex2bin[14]+" ");

break;

case 'f':

System.out.print(hex2bin[15]+" ");

break;

}

}

}

}