X-Git-Url: https://git.pterodactylus.net/?a=blobdiff_plain;f=src%2Fnet%2Fpterodactylus%2Futil%2Fnumber%2FHex.java;h=de7929e7cfe65e7982a67bd6c9a71055ed80494c;hb=1318ca0dedd3b2c0e5457979b0d4ec111df6fa8d;hp=36cca067a1d5a7b1361b4625dfb08416b95ccf23;hpb=8f3a1fc02cb969beeef635b182c88a68ec3a2d03;p=jSite2.git diff --git a/src/net/pterodactylus/util/number/Hex.java b/src/net/pterodactylus/util/number/Hex.java index 36cca06..de7929e 100644 --- a/src/net/pterodactylus/util/number/Hex.java +++ b/src/net/pterodactylus/util/number/Hex.java @@ -21,26 +21,68 @@ package net.pterodactylus.util.number; /** * Conversion routines for handling hexadecimal numbers. - * + * * @author David ‘Bombe’ Roden <bombe@freenetproject.org> - * @version $Id$ */ public class Hex { /** * Converts the given byte array to a hexadecimal string. - * + * * @param dataBytes * The bytes to convert * @return A string of hexadecimal numbers */ public static String toHex(byte[] dataBytes) { StringBuilder hexString = new StringBuilder(dataBytes.length * 2); - for (byte dataByte: dataBytes) { + for (byte dataByte : dataBytes) { String hexByte = "0" + Integer.toHexString(dataByte & 0xff); hexString.append(hexByte.substring(hexByte.length() - 2)); } 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) + * @throw NumberFormatException if the given string is not the hexadecimal + * representation of a byte array + */ + public static byte[] toByte(String hexString) { + if ((hexString.length() & 0x01) == 0x01) { + /* odd length, this is not correct. */ + throw new NumberFormatException("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; + } + }