From: David ‘Bombe’ Roden Date: Sat, 23 May 2009 15:18:48 +0000 (+0200) Subject: Add toByte() method. X-Git-Url: https://git.pterodactylus.net/?a=commitdiff_plain;h=2e719ee43cf1b21c9445c67a0707e8373d77ee66;p=jSite2.git Add toByte() method. --- diff --git a/src/net/pterodactylus/util/number/Hex.java b/src/net/pterodactylus/util/number/Hex.java index 246fa41..3f6145f 100644 --- a/src/net/pterodactylus/util/number/Hex.java +++ b/src/net/pterodactylus/util/number/Hex.java @@ -61,4 +61,26 @@ public class Hex { return hexString.toString(); } + /** + * Decodes a hexadecimal string into a byte array. + * + * @param hexString + * The hexadecimal representation to decode + * @return The decoded byte array + * @see Integer#parseInt(java.lang.String, int) + */ + public static byte[] toByte(String hexString) { + if ((hexString.length() & 0x01) == 0x01) { + /* odd length, this is not correct. */ + throw new IllegalArgumentException("hex string must have even length."); + } + byte[] dataBytes = new byte[hexString.length() / 2]; + for (int stringIndex = 0; stringIndex < hexString.length(); stringIndex += 2) { + String hexNumber = hexString.substring(stringIndex, stringIndex + 2); + byte dataByte = (byte) Integer.parseInt(hexNumber, 16); + dataBytes[stringIndex / 2] = dataByte; + } + return dataBytes; + } + }