/** * Take the incoming String of hex encoded data and convert to the raw byte values. * <p> * The characters in the incoming String are processed in pairs with two chars of a pair * being converted to a single byte. * * @param toConvert - the hex encoded String to convert. * @return the raw byte array. */ public static byte[] convertFromHex(final String toConvert) { return convertFromHex(toConvert.toCharArray()); } }
/** * Take the incoming character of hex encoded data and convert to the raw byte values. * <p> * The characters in the incoming array are processed in pairs with two chars of a pair * being converted to a single byte. * * @param toConvert - the hex encoded String to convert. * @return the raw byte array. */ public static byte[] convertFromHex(final char[] toConvert) { if (toConvert.length % 2 != 0) { throw new IllegalArgumentException("The supplied character array must contain an even number of hex chars."); } byte[] response = new byte[toConvert.length / 2]; for (int i = 0; i < response.length; i++) { int posOne = i * 2; response[i] = (byte)(toByte(toConvert, posOne) << 4 | toByte(toConvert, posOne+1)); } return response; }
/** * Create a PostgisGeometry using the supplied PostGIS Hex EWKB string. * SRID is extracted from the EWKB */ public static PostgisGeometry fromHexEwkb(String hexEwkb) { byte[] ewkb = HexConverter.convertFromHex(hexEwkb); return fromEwkb(ewkb); }
@Test(expected=IllegalArgumentException.class) public void shouldRejectNonHexCharacter() { HexConverter.convertFromHex("GG"); } }
@Test(expected=IllegalArgumentException.class) public void shouldRejectStringOfWrongLength() { HexConverter.convertFromHex("1"); }
@Test public void shouldConvertHexString() { byte[] bytes = HexConverter.convertFromHex("00010A0B0F106364657F8081FF"); assertThat(bytes).isEqualTo(new byte[] {0, 1, 10, 11, 15, 16, 99, 100, 101, 127, -128, -127, -1}); }