
net.dongliu.commons.codec.Hexes Maven / Gradle / Ivy
package net.dongliu.commons.codec;
/**
* Utils method for hex
*
* @author Liu Dong
*/
public class Hexes {
private static final char[] hexArray = "0123456789ABCDEF".toCharArray();
private static final char[] hexArrayLower = "0123456789abcdef".toCharArray();
/**
* Convert bytes to hex string in upper case. Return null if bytes is null
*/
public static String hexUpper(byte[] bytes) {
char[] hexChars = new char[bytes.length * 2];
for (int j = 0; j < bytes.length; j++) {
int v = bytes[j] & 0xFF;
hexChars[j * 2] = hexArray[v >>> 4];
hexChars[j * 2 + 1] = hexArray[v & 0x0F];
}
return new String(hexChars);
}
/**
* Convert bytes to hex string in lower case. Return null if bytes is null
*/
public static String hexLower(byte[] bytes) {
char[] hexChars = new char[bytes.length * 2];
for (int j = 0; j < bytes.length; j++) {
int v = bytes[j] & 0xFF;
hexChars[j * 2] = hexArrayLower[v >>> 4];
hexChars[j * 2 + 1] = hexArrayLower[v & 0x0F];
}
return new String(hexChars);
}
/**
* Convert hex string back to bytes. Return null if str is null.
*/
public static byte[] decode(CharSequence str) {
int len = str.length();
byte[] data = new byte[len / 2];
for (int i = 0; i < len; i += 2) {
data[i / 2] = (byte) ((Character.digit(str.charAt(i), 16) << 4)
+ Character.digit(str.charAt(i + 1), 16));
}
return data;
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy