java Byte.parseByte throw exception java.lang.NumberFormatException

 Java 에서 개발중에 16진수 값으로 구성된 String type의 Mac 주소를 String을 Byte Array로 변경하기 위해 다음의 코드를 작성하였다.


1
2
3
4
5
String temp[] = strMacAddr.split("(?<=\\G..)");
byte[] macAddr = new byte[temp.length];
for (int i = 0; i < macAddr.length; i++) { 
 macAddr[i] = Byte.parseByte(temp[i], 16);
}

여기서 잘 실행될줄 알았지만... java.lang.NumberFormatException이 발생했다. 이유는 java의 모든 정수형 primitive type은 signed value 이기 때문이다. unsigned를 지원하지 않는 이유는 찾아보면 많다 ㅋ
다음은 java를 만든 james gosling 횽님의 인터뷰이다.
(발췌 : http://www.gotw.ca/publications/c_family_interview.htm)

Gosling: For me as a language designer, which I don't really count myself as these days, what "simple" really ended up meaning was could I expect J. Random Developer to hold the spec in his head. That definition says that, for instance, Java isn't -- and in fact a lot of these languages end up with a lot of corner cases, things that nobody really understands. Quiz any C developer about unsigned, and pretty soon you discover that almost no C developers actually understand what goes on with unsigned, what unsigned arithmetic is. Things like that made C complex. The language part of Java is, I think, pretty simple. The libraries you have to look up.

돌아와서 Byte 의 범위가 (-7F ~ 7F) 의 범위를 가지기 때문에 FF, DC 등의 값은 앞서 말한 exception이 발생한다. 이러한 이유로 unsigned byte에 대한 parsing은 다음과 같이 코드를 작성해야 한다.

1
2
3
4
5
String temp[] = strMacAddr.split("(?<=\\G..)");
byte[] macAddr = new byte[temp.length];
for (int i = 0; i < macAddr.length; i++) { 
 macAddr[i] = (byte)(Integer.parseInt(temp[i], 16) & 0xFF);
}


댓글

이 블로그의 인기 게시물

Raspberry pi 한글 설정 및 chromium 설치

Google Test를 이용한 Class의 Private/Protected Member Test