Stuart McCulloch | 3fdcd85 | 2011-10-17 10:31:43 +0000 | [diff] [blame] | 1 | package aQute.lib.hex; |
| 2 | |
| 3 | import java.io.*; |
| 4 | |
| 5 | |
| 6 | /* |
| 7 | * Hex converter. |
| 8 | * |
| 9 | * TODO Implement string to byte[] |
| 10 | */ |
| 11 | public class Hex { |
| 12 | byte[] data; |
| 13 | final static char[] HEX = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'}; |
| 14 | public final static byte[] toByteArray(String string) { |
| 15 | string = string.trim(); |
| 16 | if ( (string.length() & 1) != 0) |
| 17 | throw new IllegalArgumentException("a hex string must have an even length"); |
| 18 | |
| 19 | byte[]out = new byte[ string.length()/2]; |
| 20 | for ( int i=0; i < out.length; i++) { |
| 21 | out[i] = (byte) (nibble(string.charAt(i*2))<<4 + nibble(string.charAt(i*2+1))); |
| 22 | } |
| 23 | return out; |
| 24 | } |
| 25 | |
| 26 | |
| 27 | public final static int nibble( char c) { |
| 28 | if (c >= '0' && c <= '9') |
| 29 | return c - '0'; |
| 30 | |
| 31 | if ( c>='A' && c<='F') |
| 32 | return c - 'A' + 10; |
| 33 | if ( c>='a' && c<='f') |
| 34 | return c - 'a' + 10; |
| 35 | |
| 36 | throw new IllegalArgumentException("Not a hex digit: " + c); |
| 37 | } |
| 38 | |
| 39 | public final static String toHexString(byte data[]) { |
| 40 | StringBuilder sb = new StringBuilder(); |
| 41 | try { |
| 42 | append(sb,data); |
| 43 | } catch (IOException e) { |
| 44 | // cannot happen with sb |
| 45 | } |
| 46 | return sb.toString(); |
| 47 | } |
| 48 | |
| 49 | public final static void append( Appendable sb, byte [] data ) throws IOException { |
| 50 | for ( int i =0; i<data.length; i++) { |
| 51 | sb.append( nibble( data[i] >> 4)); |
| 52 | sb.append( nibble( data[i])); |
| 53 | } |
| 54 | } |
| 55 | |
| 56 | private final static char nibble(int i) { |
| 57 | return HEX[i & 0xF]; |
| 58 | } |
| 59 | } |