2012년 6월 18일 월요일

자바 int -> char 변환

예를 들어 int a = 1 이라고 했을 때
char형으로 형변환하는 것이 아닌 문자 1로 바꾸는 방법

Java 공부를 하다가 int 값을 "문자열"로 변경하는 방법은 인터넷에서 검색이 많이 되는데
유독 int값 그대로를 문자로 바꾸는 방법이 안나와서 약 15분간 삽질하다가 알아낸거라 
잊지 않기 위해 포스팅을 합니다.

java.lang 패키지의 Character 클래스의 메소드로 forDigit()가 있습니다.
API문서에서 정의하는 forDigit()의 설명을 보면

public static char forDigit(int digit, int radix)

Determines the character representation for a specific digit in the specified radix. If the value of radix is not a valid radix, or the value of digit is not a valid digit in the specified radix, the null character ('\u0000') is returned.

The radix argument is valid if it is greater than or equal to MIN_RADIX and less than or equal to MAX_RADIX. The digit argument is valid if 0 <=digit < radix.

If the digit is less than 10, then '0' + digit is returned. Otherwise, the value 'a' + digit - 10 is returned.


예제를 들어 설명하자면

  1. int a = 1;  
  2. char c = a;  
  3. System.out.println(c);  
  4.   
  5. 결과 : ^A  

를 할 경우 c의 값을 출력하게되면 ASCII값 1에 해당하는 ^A가 됩니다.
하지만 forDigit() 사용하게되면 문자 1에 해당하는 ASCII 코드 값인 49를 반환하게 됩니다.

  1. int a = 1;  
  2. char c = Character.forDigit(a, 10);  
  3. System.out.println(c);  
  4.   
  5. 결과 : 1  



갑자기 왜 뜬금없이 int형을 문자형 char로 변경하는 것에 관심을 가지게 되었냐면

  1. FileOutputStream fos = new FileOutputStrea("test.txt");  
  2. for(int i = 0; i < 10; i++)  
  3. {  
  4.     fos.write(i);  
  5. }  

test.txt에 0에서부터 9까지 기록하게 하기위함이었는데
막상 결과는 다르게 나와서 해결하려고 보니............


댓글 없음:

댓글 쓰기