Never been to DZone Snippets before?

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

About this user

Steven Devijver

« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS 

Convert a long to HEX value and the other way around

Handy to convert MD5 or SHA-1 hash values.

   1  
   2  	public static long hexToLong(byte[] bytes) {
   3  
   4  		if (bytes.length > 16) {
   5  			throw new IllegalArgumentException("Byte array too long (max 16 elements)");
   6  		}
   7  		long v = 0;
   8  		for (int i = 0; i < bytes.length; i += 2) {
   9  			byte b1 = (byte) (bytes[i] & 0xFF);
  10  
  11  			b1 -= 48;
  12  			if (b1 > 9) b1 -= 39;
  13  
  14  			if (b1 < 0 || b1 > 15) {
  15  				throw new IllegalArgumentException("Illegal hex value: " + bytes[i]);
  16  			}
  17  
  18  			b1 <<=4;
  19  
  20  			byte b2 = (byte) (bytes[i + 1] & 0xFF);
  21  			b2 -= 48;
  22  			if (b2 > 9) b2 -= 39;
  23  
  24  			if (b2 < 0 || b2 > 15) {
  25  				throw new IllegalArgumentException("Illegal hex value: " + bytes[i + 1]);
  26  			}
  27  
  28  			v |= (((b1 & 0xF0) | (b2 & 0x0F))) & 0x00000000000000FFL ;
  29  
  30  			if (i + 2 < bytes.length) v <<= 8;
  31  		}
  32  
  33  		return v;
  34  	}
  35  
  36  	public static byte[] longToHex(final long l) {
  37  		long v = l & 0xFFFFFFFFFFFFFFFFL;
  38  
  39  		byte[] result = new byte[16];
  40  		Arrays.fill(result, 0, result.length, (byte)0);
  41  
  42  		for (int i = 0; i < result.length; i += 2) {
  43  			byte b = (byte) ((v & 0xFF00000000000000L) >> 56);
  44  
  45  			byte b2 = (byte) (b & 0x0F);
  46  			byte b1 = (byte) ((b >> 4) & 0x0F);
  47  
  48  			if (b1 > 9) b1 += 39;
  49  			b1 += 48;
  50  
  51  			if (b2 > 9) b2 += 39;
  52  			b2 += 48;
  53  
  54  			result[i] = (byte) (b1 & 0xFF);
  55  			result[i + 1] = (byte) (b2 & 0xFF);
  56  
  57  			v <<= 8;
  58  		}
  59  
  60  		return result;
  61  	}
  62  


And tests:

   1  
   2  	public void testHexToLong() throws Exception {
   3  		assertEquals(-7057002501900618110L, NumberUtils.hexToLong("9e107d9d372bb682".getBytes()));
   4  		assertEquals(-10908158098650842L, NumberUtils.hexToLong("ffd93f1687604926".getBytes()));
   5  	}
   6  
   7  	public void testLongToHex() throws Exception {
   8  		assertEquals("9e107d9d372bb682", new String(NumberUtils.longToHex(-7057002501900618110L)));
   9  		assertEquals("ffd93f1687604926", new String(NumberUtils.longToHex(-10908158098650842L)));
  10  	}
« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS