move Text hex to Encoder/Decoder
This commit is contained in:
@@ -4,6 +4,7 @@ import com.imyeyu.java.bean.timi.TimiCode;
|
||||
import com.imyeyu.java.bean.timi.TimiException;
|
||||
|
||||
import java.io.StringWriter;
|
||||
import java.io.UnsupportedEncodingException;
|
||||
import java.net.URLDecoder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Base64;
|
||||
@@ -102,4 +103,42 @@ public class Decoder {
|
||||
}
|
||||
return URLDecoder.decode(url, StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
/**
|
||||
* 16 进制字符串转字节数据
|
||||
*
|
||||
* @param hex 16 进制字符串
|
||||
* @return 字节数据
|
||||
* @throws UnsupportedEncodingException 不支持的编码
|
||||
*/
|
||||
public static byte[] hex(String hex) throws UnsupportedEncodingException {
|
||||
final char[] c = hex.toCharArray();
|
||||
final byte[] b = new byte[c.length >> 1];
|
||||
|
||||
final int len = c.length;
|
||||
if ((len & 0x01) != 0) {
|
||||
throw new UnsupportedEncodingException("Odd number of characters.");
|
||||
}
|
||||
|
||||
final int outLen = len >> 1;
|
||||
if (c.length < outLen) {
|
||||
throw new UnsupportedEncodingException("Output array is not large enough to accommodate decoded data.");
|
||||
}
|
||||
for (int i = 0, j = 0; j < len; i++) {
|
||||
int f = toDigit(c[j], j) << 4;
|
||||
j++;
|
||||
f = f | toDigit(c[j], j);
|
||||
j++;
|
||||
b[i] = (byte) (f & 0xFF);
|
||||
}
|
||||
return b;
|
||||
}
|
||||
|
||||
private static int toDigit(final char ch, final int index) throws UnsupportedEncodingException {
|
||||
final int digit = Character.digit(ch, 16);
|
||||
if (digit == -1) {
|
||||
throw new UnsupportedEncodingException("Illegal hexadecimal character " + ch + " at index " + index);
|
||||
}
|
||||
return digit;
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user