1 6 7 package net.sourceforge.jcetaglib.tools; 8 9 import java.io.*; 10 import java.math.BigInteger ; 11 12 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 32 public static String 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 48 public static byte[] decode(String dataStr) { 49 50 if ((dataStr.length() & 0x01) == 0x01) 51 dataStr = new String (dataStr + "0"); 52 BigInteger cI = new BigInteger (dataStr, 16); 53 byte[] data = cI.toByteArray(); 54 55 return data; 56 } 58 public static void main(String [] 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 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 e) { 85 e.printStackTrace(); 86 } 87 88 } 90 } 92 | Popular Tags |