Upgrade
Sign In : Sign Up : Blog : Search: Language : Help :
This website is now frozen, please migrate your content to BotLibre.com or BotLibre.biz
Java

How to hex encode and decode a byte array

by jamesssss posted Aug 27 2014, 9:45

HEX is a standard why to convert from binary data to character data. It is useful in web development when you need to encode binary data in HTML or XML. HEX conversion is also useful when storing binary data in a database character field.

HEX is a base 16 numbering system, so 1-9 are the same, and the letters A-F are used for 10-15. So in HEX 10 = 16, 100 = 256, AA = 170, FF = 255. HEX conversion encodes each byte as two HEX characters, so the encoded string will be twice the size of the original byte array.

The following code will convert between a byte[] and HEX String, and back. Feel free to use the code as you wish (public domain).

public static String bytesToHex(byte[] bytes) { char[] hex = new char[bytes.length * 2]; for (int i = 0; i < bytes.length; i++) { int v = bytes[i] & 0xFF; hex[i * 2] = hex[v >>> 4]; hex[i * 2 + 1] = hex[v & 0x0F]; } return new String(hex); } public static byte[] hexToBytes(String hex) { int length = hex.length(); byte[] data = new byte[length / 2]; for (int i = 0; i < length ; i += 2) { data[i / 2] = (byte) ((Character.digit(hex.charAt(i), 16) << 4) + Character.digit(hex.charAt(i+1), 16)); } return data; }


Id: 320217
Tags: hex, binary, conversion, encode, decode
Posted: Aug 27 2014, 9:45
Updated: Mar 27 2015, 16:12
Replies: 0
Views: 1137, today: 2, week: 3, month: 3
I'm sure
Flag graphic as offensive, or in violation of site rules