문서의 선택한 두 판 사이의 차이를 보여줍니다.
양쪽 이전 판 이전 판 다음 판 | 이전 판 | ||
java:number [2015/07/10 18:04] kwon37xi [숫자들 간의 Type 무시 비교 / Comparing numbers] |
java:number [2021/02/17 00:09] (현재) kwon37xi |
||
---|---|---|---|
줄 5: | 줄 5: | ||
<code java> | <code java> | ||
public int compare(final Number x, final Number y) { | public int compare(final Number x, final Number y) { | ||
- | if(isSpecial(x) || isSpecial(y)) | + | if(isSpecial(x) || isSpecial(y)) |
return Double.compare(x.doubleValue(), | return Double.compare(x.doubleValue(), | ||
- | else | + | |
+ | // x, y의 class가 동일하다면 y.compareTo(y) 만하도록 처리하면 성능이 좋아질 수 있다. | ||
+ | // x, y의 class가 다를 경우에만 BigDecimal로 변환한다. | ||
return toBigDecimal(x).compareTo(toBigDecimal(y)); | return toBigDecimal(x).compareTo(toBigDecimal(y)); | ||
+ | } | ||
} | } | ||
줄 28: | 줄 31: | ||
return new BigDecimal(number.longValue()); | return new BigDecimal(number.longValue()); | ||
if(number instanceof Float || number instanceof Double) | if(number instanceof Float || number instanceof Double) | ||
- | return new BigDecimal(number.doubleValue()); | + | |
+ | | ||
try { | try { | ||
줄 40: | 줄 44: | ||
</ | </ | ||
* '' | * '' | ||
+ | * 비교 대상이 되는 두 객체가 동일 클래스 인스턴스라면 '' | ||
* 특수한 숫자 객체를 제외한 int 계열의 숫자는 바로 '' | * 특수한 숫자 객체를 제외한 int 계열의 숫자는 바로 '' | ||
+ | |||
+ | ===== Hex 16진수 ===== | ||
+ | * 숫자를 16진수로 바꾸기 | ||
+ | * [[http:// | ||
+ | * 그러나 hex는 보통 2자리씩 이뤄지는데 때로 앞자리가 0으로 시작하면 홀수자리 hex 문자열이 나올 수도 있다. 이때, [[http:// | ||
+ | |||
+ | <code java> | ||
+ | // Long 값을 16자리 Hex 문자열로 | ||
+ | String hex = String.format(" | ||
+ | </ | ||
+ | * [[https:// | ||
+ | * Apache Commons Codec | ||
+ | <code java> | ||
+ | import org.apache.commons.codec.binary.Hex; | ||
+ | ... | ||
+ | Hex.encodeHexString(someByteArray)); | ||
+ | </ | ||
+ | * 순수 Java | ||
+ | |||
+ | <code java> | ||
+ | byte bytes[] = {(byte)0, (byte)0, (byte)134, (byte)0, (byte)61}; | ||
+ | String hex = javax.xml.bind.DatatypeConverter.printHexBinary(bytes); | ||
+ | </ | ||
+ | |||
+ | * 순수 Java - Java 8 이전 | ||
+ | <code java> | ||
+ | public static String bytesToHex(byte[] bytes) { | ||
+ | char[] hexChars = new char[bytes.length * 2]; | ||
+ | for (int j = 0; j < bytes.length; | ||
+ | int v = bytes[j] & 0xFF; | ||
+ | hexChars[j * 2] = HEX_ARRAY[v >>> | ||
+ | hexChars[j * 2 + 1] = HEX_ARRAY[v & 0x0F]; | ||
+ | } | ||
+ | return new String(hexChars); | ||
+ | } | ||
+ | </ | ||
+ | |||
+ | * 순수 Java - Java 9 이후 | ||
+ | <code java> | ||
+ | public static String bytesToHex(byte[] bytes) { | ||
+ | byte[] hexChars = new byte[bytes.length * 2]; | ||
+ | for (int j = 0; j < bytes.length; | ||
+ | int v = bytes[j] & 0xFF; | ||
+ | hexChars[j * 2] = HEX_ARRAY[v >>> | ||
+ | hexChars[j * 2 + 1] = HEX_ARRAY[v & 0x0F]; | ||
+ | } | ||
+ | return new String(hexChars, | ||
+ | } | ||
+ | </ |