KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > net > sourceforge > jcetaglib > tools > Hex


1 /*
2  * Copyright 1998-2000 Sun Microsystems, Inc. All Rights Reserved.
3  *
4  * Modified by Tomas Gustavsson
5  */

6
7 package net.sourceforge.jcetaglib.tools;
8
9 import java.io.*;
10 import java.math.BigInteger JavaDoc;
11
12 /**
13  * This class implements a hex decoder, decoding a string with hex-characters into
14  * the binary form.
15  *
16  * @version $Id: Hex.java,v 1.4 2004/04/15 07:28:36 hamgert Exp $
17  *
18  */

19 public class Hex {
20
21     static private final char hex[] = {
22         '0', '1', '2', '3', '4', '5', '6', '7',
23         '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
24     };
25
26     /**
27      * Encodar binärt till hex
28      *
29      *@param dataStr bin-representation av data
30      *@return Hex-representation av data
31      **/

32     public static String JavaDoc encode(byte[] dataStr) {
33         StringWriter w = new StringWriter();
34         for (int i = 0; i < dataStr.length; i++) {
35             int b = dataStr[i];
36             w.write(hex[((b >> 4) & 0xF)]);
37             w.write(hex[((b >> 0) & 0xF)]);
38         }
39         return w.toString();
40     }
41
42     /**
43      * Decodar hex till binärt
44      *
45      *@param dataStr Sträng innehållande hex-representation av data
46      *@return byte[] innhållande binär representation av data
47      **/

48     public static byte[] decode(String JavaDoc dataStr) {
49
50         if ((dataStr.length() & 0x01) == 0x01)
51             dataStr = new String JavaDoc(dataStr + "0");
52         BigInteger JavaDoc cI = new BigInteger JavaDoc(dataStr, 16);
53         byte[] data = cI.toByteArray();
54
55         return data;
56     } //decode
57

58     public static void main(String JavaDoc[] args) {
59         if (args.length != 3) {
60             System.out.println("Usage: HexStrToBin enc/dec <infileName> <outfilename>");
61             System.exit(1);
62         }
63         try {
64             ByteArrayOutputStream os = new ByteArrayOutputStream();
65             InputStream in = new FileInputStream(args[1]);
66             int len = 0;
67             byte buf[] = new byte[1024];
68             while ((len = in.read(buf)) > 0)
69                 os.write(buf, 0, len);
70             in.close();
71             os.close();
72
73             byte[] data = null;
74             if (args[0].equals("dec"))
75                 data = decode(os.toString());
76             else {
77                 String JavaDoc strData = encode(os.toByteArray());
78                 data = strData.getBytes();
79             }
80
81             FileOutputStream fos = new FileOutputStream(args[2]);
82             fos.write(data);
83             fos.close();
84         } catch (Exception JavaDoc e) {
85             e.printStackTrace();
86         }
87
88     } //main
89

90 } // Hex
91

92
Popular Tags