Base16
编码的Java语言实现如下:
private static final String base16EncodeTable = "0123456789ABCDEF";
public static String base16Encode(byte[] data) {
if (data == null || data.length == 0) {
return "";
}
StringBuilder result = new StringBuilder(data.length * 2);
for (int i = 0; i < data.length; i++) {
//向右移动4bit,获得高4bit
int highByte = (data[i] >> 4) & 0x0F;
//与0x0f做位与运算,获得低4bit
int lowByte = data[i] & 0x0F;
result.append(base16EncodeTable.charAt(highByte));
result.append(base16EncodeTable.charAt(lowByte));
}
return result.toString();
}
Java语言中还可以使用如下简便方法实现Base16
编码:
public static String base16Encode(byte[] data) {
StringBuilder result = new StringBuilder(bytes.length * 2);
for (byte b : bytes) { // 使用String的format方法进行转换
result.append(String.format("%02X", new Integer(b & 0xFF)));
}
return result.toString();
}
Base16
解码的Java语言实现如下:
//把16进制字符转换成10进制表示的数字
private static int hex2dec(char c) {
if ('0' <= c && c <= '9') {
return c - '0';
} else if ('a' <= c && c <= 'f') {
return c - 'a' + 10;
} else if ('A' <= c && c <= 'F') {
return c - 'A' + 10;
} else {
return 0;
}
}
public static byte[] base16Decode(String input) {
int inputLength = input.length();
int halfInputLength = inputLength / 2;
byte[] output = new byte[halfInputLength];
for (int i = 0; i < halfInputLength; i++) {
//16进制数字转换为10进制数字的过程
output[i] = (byte) (hex2dec(input.charAt(2 * i)) * 16 + hex2dec(input.charAt(2 * i + 1)));
}
return output;
}