1 10 package org.mmbase.util.transformers; 11 12 import java.util.HashMap ; 13 import java.util.Map ; 14 15 23 24 public class Hex extends ByteArrayToCharTransformer implements ByteToCharTransformer, ConfigurableTransformer { 25 private final static String ENCODING = "HEX"; 26 private final static int HEX = 1; 27 28 int to = HEX; 29 30 public void configure(int t) { 31 to = t; 32 } 33 34 37 38 public Map transformers() { 39 HashMap h = new HashMap (); 40 h.put(ENCODING, new Config(Hex.class, HEX, "Encoding bytearrays to and from a hexidecimal string")); 41 return h; 42 } 43 44 45 48 public String transform(byte[] bytes) { 49 StringBuffer strbuf = new StringBuffer (bytes.length * 2); 50 for (int i = 0; i<bytes.length; i++) { 51 if (((int) bytes[i] & 0xff) < 0x10) { 52 strbuf.append("0"); 53 } 54 strbuf.append(Long.toString((int) bytes[i] & 0xff, 16)); 55 } 56 57 return strbuf.toString(); 58 } 59 60 66 public byte[] transformBack(String r) { 67 try { 68 int strlen = r.length(); 69 byte[] retval = new byte[strlen/2]; 70 for (int i=0; i<strlen; i+=2) { 71 char c1 = r.charAt(i); 72 char c2 = r.charAt(i+1); 73 int b = 0; 74 if (c1 >= '0' && c1 <= '9') { 75 b += 16 * (c1 - '0'); 76 } else { 77 b += 16 * (10 + c1 - 'a'); 78 } 79 if (c2 >= '0' && c2 <= '9') { 80 b += (c2 - '0'); 81 } else { 82 b += (10 + c2 - 'a'); 83 } 84 retval[i/2] = (byte)b; 85 } 86 return retval; 87 } catch (Exception e) { 88 e.printStackTrace(); 89 throw new IllegalArgumentException ("the entered string to decode properly was wrong: " + e); 90 } 91 } 92 93 public String getEncoding() { 94 return ENCODING; 95 } 96 } 97 | Popular Tags |