글쓴이 :박찬우 2000년 5월 20일 11:58:14
In Reply to: int를 2진수로(00110011...)바꿔주는 메소드가 있나요? posted by 준홍 on 2000년 5월 20일 10:24:42:
사용할 수 있는 메서드는 다음과 같습니다.
public static String toBinaryString(int i)
public static int parseInt(String s, int radix) throws NumberFormatException
두 번째 것을 쓰면 입력받은 문자열형 숫자들을 바로
원하는 진법으로 변환할 수 있는 장점이 있습니다.
여기에서는 첫번째 것을 이용한 예를 듭니다.
요구하는 숫자가 제대로 입력되면 통과하고
그렇지 않으면 재차 올바른 입력을 요구하도록 했습니다.
1바이트 스트림과 2바이트 스트림을 연결하는 역할의
InputStreamReader도 잘 봐두세요.
다음은 그 예입니다.
/**
+ 작성: 박찬우
+ e-mail: nucha@dremawiz.com
+ homepage: http://my.dreamwiz.com/nucha
*/
import java.io.*;
public class BinaryTest
{
public static void main(String[] args) throws IOException
{
boolean checkInput = false;
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String strIN = null;
int intIN = 0;
while (!checkInput)
{
System.out.print("정수를 입력: " );
strIN = in.readLine();
try
{
intIN = Integer.parseInt(strIN);
checkInput = true;
}
catch (NumberFormatException ex)
{
System.out.println("정수를 대입해주세요\n");
}
}
System.out.println("\n입력하신 숫자: " + intIN);
String strBIN = Integer.toBinaryString(intIN);
System.out.println("이진법으로 변환 후 결과: " + strBIN);
System.out.println("\n종료하시려면 엔터키를 누르세요.");
in.readLine();
}
}
다음은 실행 결과입니다.
정수를 입력: 5g7fdf
정수를 대입해주세요
정수를 입력: a
정수를 대입해주세요
정수를 입력: 67
입력하신 숫자: 67
이진법으로 변환 후 결과: 1000011
종료하시려면 엔터키를 누르세요.