In software programming, sometime you may want to convert a long integer or integer into hexadecimal string for viewing purpose or also as a text format to be stored in text file or database.
The Java API itself does not have a class or function to convert a long into a fixed 16 characters hexadecimal string or an integer into fixed 8 characters hexadecimal string.
The Java’s Long.toHexString(long i)
or Integer.toHexString(int i)
only able to convert the integer value to a string of ASCII digits in hexadecimal (base 16) with no extra leading 0s and it does not support the reverse way (from hexadecimal string to long integer value).
I wrote a simple class to convert a long integer value into fixed length hexadecimal string and vice versa.
public class Hex { private final static char[] HEX = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; public static long toLong(String hexadecimal) throws NumberFormatException{ char[] chars; char c; long value; int i; byte b; if (hexadecimal == null) throw new IllegalArgumentException(); chars = hexadecimal.toUpperCase().toCharArray(); if (chars.length != 16) throw new HexValueException("Incomplete hex value"); value = 0; b = 0; for (i = 0; i < 16; i++) { c = chars[i]; if (c >= '0' && c <= '9') { value = ((value << 4) | (0xff & (c - '0'))); } else if (c >= 'A' && c <= 'F') { value = ((value << 4) | (0xff & (c - 'A' + 10))); } else { throw new NumberFormatException("Invalid hex character: " + c); } } return value; } public static String fromLong(long value) { char[] hexs; int i; int c; hexs = new char[16]; for (i = 0; i < 16; i++) { c = (int)(value & 0xf); hexs[16-i-1] = HEX[c]; value = value >> 4; } return new String(hexs); } public static void main(String[] arg) { int i; long[] test = { -1234567890, 1234567890, 987654321, -987654321, 0xFFFFFFFFFFFFFFFFl, 0x1234567890FFFFFFl }; long v; String s; for (i = 0; i < test.length; i++) { s = Hex.fromLong(test[i]); v = 0; try { v = Hex.toLong(s); } catch(NumberFormatException ex) { System.err.println(ex.getMessage()); } if (v != test[i]) { System.err.println("Not same " + test[i] + " " + v); System.exit(1); } } System.err.println("Test completed satisfactory"); } }
To convert long integer into 16 characters hexadecimal string:
String result = Hex.fromLong(1234567890);
To convert 16 characters hexadecimal string into long integer:
long result = Hex.toLong("00000000499602D2");
The Hex class above can be easily modified to support integer and short value by changing the data type and its size (e.g. integer has 4 bytes or 8 characters of hexadecimal and short has 2 bytes or 4 characters of hexadecimal).
Olivier says
You could also use
Long.toString(, 16)
szehau says
Hi, Long.toString() does not return a fixed size string. 🙂