3 public static void main(String
[] argv
) throws Throwable
{
4 byte[] b
= new byte[] {
5 0x01, 0x23, 0x45, 0x67, (byte) 0x89, (byte) 0xab,
6 (byte) 0xcd, (byte) 0xef
8 String s
= "0123456789ABCDEF";
9 System
.out
.println(toString(b
));
10 System
.out
.println(s
);
11 System
.out
.println(toString(toBytesFromString(s
)));
14 // The following comes from the GNU Crypto project gnu.crypto.util.Util
16 private static final char[] HEX_DIGITS
= {
17 '0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'
20 public static byte[] toBytesFromString(String s
) {
21 int limit
= s
.length();
22 byte[] result
= new byte[((limit
+ 1) / 2)];
24 if ((limit
% 2) == 1) {
25 result
[j
++] = (byte) fromDigit(s
.charAt(i
++));
29 (byte)((fromDigit(s
.charAt(i
++)) << 4) | fromDigit(s
.charAt(i
++)));
34 public static int fromDigit(char c
) {
35 if (c
>= '0' && c
<= '9') {
37 } else if (c
>= 'A' && c
<= 'F') {
39 } else if (c
>= 'a' && c
<= 'f') {
42 throw new IllegalArgumentException("Invalid hexadecimal digit: " + c
);
45 public static String
toString(byte[] ba
) {
46 return toString(ba
, 0, ba
.length
);
49 public static final String
toString(byte[] ba
, int offset
, int length
) {
50 char[] buf
= new char[length
* 2];
51 for (int i
= 0, j
= 0, k
; i
< length
; ) {
53 buf
[j
++] = HEX_DIGITS
[(k
>>> 4) & 0x0F];
54 buf
[j
++] = HEX_DIGITS
[ k
& 0x0F];
56 return new String(buf
);