X-Git-Url: https://git.pterodactylus.net/?a=blobdiff_plain;ds=sidebyside;f=src%2Fnet%2Fpterodactylus%2Futil%2Fnumber%2FHex.java;h=3f6145f75b0cd9c6e280d4c66708d0b2423c6ffc;hb=2e719ee43cf1b21c9445c67a0707e8373d77ee66;hp=f81ec05d5abe0b7ff30404fd090739e32033349a;hpb=c63257e8cc0ba1a5aca9364b22171abe7279d479;p=jSite2.git diff --git a/src/net/pterodactylus/util/number/Hex.java b/src/net/pterodactylus/util/number/Hex.java index f81ec05..3f6145f 100644 --- a/src/net/pterodactylus/util/number/Hex.java +++ b/src/net/pterodactylus/util/number/Hex.java @@ -42,4 +42,45 @@ public class Hex { return hexString.toString(); } + /** + * Converts the given value to a hexadecimal string and zero-pads it to the + * given number of digits. + * + * @param value + * The value to convert + * @param digits + * The number of digits + * @return The formatted hexadecimal value + */ + public static String toHex(long value, int digits) { + StringBuilder hexString = new StringBuilder(); + hexString.append(Long.toHexString(value)); + while (hexString.length() < digits) { + hexString.insert(0, '0'); + } + 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; + } + }