Home > Coding > From bytes to hex

From bytes to hex

November 27th, 2007 Leave a comment Go to comments

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 Tags:
  1. No comments yet.
  1. No trackbacks yet.