Convert to/from Hex string
import java.util.Calendar;
import java.util.Date;
public class Util{
/**
* Creates byte array representation of HEX string.<br>
*
* @param s
* string to parse
* @return
*/
public static byte[] fromHexString(String s) {
int length = s.length() / 2;
byte[] bytes = new byte[length];
for (int i = 0; i < length; i++) {
bytes[i] = (byte) ((Character.digit(s.charAt(i * 2), 16) << 4) | Character
.digit(s.charAt((i * 2) + 1), 16));
}
return bytes;
}
/**
* Creates HEX String representation of supplied byte array.<br/>
* Each byte is represented by a double character element from 00 to ff
*
* @param fieldData
* to be tringed
* @return
*/
public static String toHexString(byte[] fieldData) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < fieldData.length; i++) {
int v = (fieldData[i] & 0xFF);
if (v <= 0xF) {
sb.append("0");
}
sb.append(Integer.toHexString(v));
}
return sb.toString();
}
}
Related examples in the same category