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