1 22 23 package org.continuent.sequoia.common.stream.encoding; 24 25 31 public class HexaEncoding 32 { 33 39 public static final String data2hex(byte[] data) 40 { 41 if (data == null) 42 return null; 43 44 int len = data.length; 45 StringBuffer buf = new StringBuffer (len * 2); 46 for (int pos = 0; pos < len; pos++) 47 buf.append(toHexChar((data[pos] >>> 4) & 0x0F)).append( 48 toHexChar(data[pos] & 0x0F)); 49 return buf.toString(); 50 } 51 52 58 public static final byte[] hex2data(String str) 59 { 60 if (str == null) 61 return new byte[0]; 62 63 int len = str.length(); 64 char[] hex = str.toCharArray(); 65 byte[] buf = new byte[len / 2]; 66 67 for (int pos = 0; pos < len / 2; pos++) 68 buf[pos] = (byte) (((toDataNibble(hex[2 * pos]) << 4) & 0xF0) | (toDataNibble(hex[2 * pos + 1]) & 0x0F)); 69 70 return buf; 71 } 72 73 79 public static char toHexChar(int i) 80 { 81 if ((0 <= i) && (i <= 9)) 82 return (char) ('0' + i); 83 else 84 return (char) ('a' + (i - 10)); 85 } 86 87 93 public static byte toDataNibble(char c) 94 { 95 if (('0' <= c) && (c <= '9')) 96 return (byte) ((byte) c - (byte) '0'); 97 else if (('a' <= c) && (c <= 'f')) 98 return (byte) ((byte) c - (byte) 'a' + 10); 99 else if (('A' <= c) && (c <= 'F')) 100 return (byte) ((byte) c - (byte) 'A' + 10); 101 else 102 return -1; 103 } 104 } 105 | Popular Tags |