3 * Copyright © 2008 David Roden
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
20 package net.pterodactylus.util.number;
23 * Conversion routines for handling hexadecimal numbers.
25 * @author David ‘Bombe’ Roden <bombe@freenetproject.org>
30 * Converts the given byte array to a hexadecimal string.
33 * The bytes to convert
34 * @return A string of hexadecimal numbers
36 public static String toHex(byte[] dataBytes) {
37 StringBuilder hexString = new StringBuilder(dataBytes.length * 2);
38 for (byte dataByte : dataBytes) {
39 String hexByte = "0" + Integer.toHexString(dataByte & 0xff);
40 hexString.append(hexByte.substring(hexByte.length() - 2));
42 return hexString.toString();
46 * Converts the given value to a hexadecimal string and zero-pads it to the
47 * given number of digits.
50 * The value to convert
52 * The number of digits
53 * @return The formatted hexadecimal value
55 public static String toHex(long value, int digits) {
56 StringBuilder hexString = new StringBuilder();
57 hexString.append(Long.toHexString(value));
58 while (hexString.length() < digits) {
59 hexString.insert(0, '0');
61 return hexString.toString();
65 * Decodes a hexadecimal string into a byte array.
68 * The hexadecimal representation to decode
69 * @return The decoded byte array
70 * @see Integer#parseInt(java.lang.String, int)
71 * @throw NumberFormatException if the given string is not the hexadecimal
72 * representation of a byte array
74 public static byte[] toByte(String hexString) {
75 if ((hexString.length() & 0x01) == 0x01) {
76 /* odd length, this is not correct. */
77 throw new NumberFormatException("hex string must have even length.");
79 byte[] dataBytes = new byte[hexString.length() / 2];
80 for (int stringIndex = 0; stringIndex < hexString.length(); stringIndex += 2) {
81 String hexNumber = hexString.substring(stringIndex, stringIndex + 2);
82 byte dataByte = (byte) Integer.parseInt(hexNumber, 16);
83 dataBytes[stringIndex / 2] = dataByte;