From bytes to hex
When creating checksums or generating keys it might be helpful sometimes to represent the key/checksum as a hexadecimal string value. The key is most of the times a byte array which will need conversion. You can convert it with the following code (java 1.5+)
public String toHexString(byte[] b){ StringBuilder sb = new StringBuilder(); for( byte hexByte : b ){ sb.append(Integer.toHexString(hexByte & 0xFF).toUpperCase()); } return sb.toString(); }
By using the 0xFF with a bitwise AND operator we ensure that the byte to be converted is unsigned.
Categories: Coding