DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Convert A Long To HEX Value And The Other Way Around

09.30.2007
| 25822 views |
  • submit to reddit
        Handy to convert MD5 or SHA-1 hash values.

	public static long hexToLong(byte[] bytes) {

		if (bytes.length > 16) {
			throw new IllegalArgumentException("Byte array too long (max 16 elements)");
		}
		long v = 0;
		for (int i = 0; i < bytes.length; i += 2) {
			byte b1 = (byte) (bytes[i] & 0xFF);

			b1 -= 48;
			if (b1 > 9) b1 -= 39;

			if (b1 < 0 || b1 > 15) {
				throw new IllegalArgumentException("Illegal hex value: " + bytes[i]);
			}

			b1 <<=4;

			byte b2 = (byte) (bytes[i + 1] & 0xFF);
			b2 -= 48;
			if (b2 > 9) b2 -= 39;

			if (b2 < 0 || b2 > 15) {
				throw new IllegalArgumentException("Illegal hex value: " + bytes[i + 1]);
			}

			v |= (((b1 & 0xF0) | (b2 & 0x0F))) & 0x00000000000000FFL ;

			if (i + 2 < bytes.length) v <<= 8;
		}

		return v;
	}

	public static byte[] longToHex(final long l) {
		long v = l & 0xFFFFFFFFFFFFFFFFL;

		byte[] result = new byte[16];
		Arrays.fill(result, 0, result.length, (byte)0);

		for (int i = 0; i < result.length; i += 2) {
			byte b = (byte) ((v & 0xFF00000000000000L) >> 56);

			byte b2 = (byte) (b & 0x0F);
			byte b1 = (byte) ((b >> 4) & 0x0F);

			if (b1 > 9) b1 += 39;
			b1 += 48;

			if (b2 > 9) b2 += 39;
			b2 += 48;

			result[i] = (byte) (b1 & 0xFF);
			result[i + 1] = (byte) (b2 & 0xFF);

			v <<= 8;
		}

		return result;
	}


And tests:

	public void testHexToLong() throws Exception {
		assertEquals(-7057002501900618110L, NumberUtils.hexToLong("9e107d9d372bb682".getBytes()));
		assertEquals(-10908158098650842L, NumberUtils.hexToLong("ffd93f1687604926".getBytes()));
	}

	public void testLongToHex() throws Exception {
		assertEquals("9e107d9d372bb682", new String(NumberUtils.longToHex(-7057002501900618110L)));
		assertEquals("ffd93f1687604926", new String(NumberUtils.longToHex(-10908158098650842L)));
	}
    

Comments

replied on Sat, 2008/02/02 - 6:34pm

alternatively, you can use Long.toHexString(long) to convert a long into a hex string; and for longs up to 2^31-1, you can use Long.parseLong(String, 16) to convert a hex string into a long