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