// Collection of code snippets by Arne Vajhøj 
// (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) 
import java.util.*;
import java.io.*;
import java.net.*;

public class SerializeToString {
    public static void main(String[] args) throws Exception {
        Vector v = new Vector();
        v.add(0,new Integer(123));
        v.add(1,new String("abc"));
        String s = encode(v);
        Vector v2 = (Vector)decode(s);
        System.out.println((Integer)v2.get(0));
        System.out.println((String)v2.get(1));
    }
    private static String encode(Object o) throws Exception {
        ByteArrayOutputStream ba = new ByteArrayOutputStream(1000);
        ObjectOutputStream oba = new ObjectOutputStream(ba);
        oba.writeObject(o);
        return hexify(ba.toByteArray());
    }
    private static Object decode(String s) throws Exception {
        ByteArrayInputStream ba = new ByteArrayInputStream(dehexify(s));
        ObjectInputStream oba = new ObjectInputStream(ba);
        return oba.readObject();
    }
    private final static String hexValue[] = { "0", "1", "2", "3",
        "4", "5", "6", "7",
        "8", "9", "A", "B",
        "C", "D", "E", "F"};
    private static String hexify(byte[] ba) {
        StringBuffer sb = new StringBuffer();
        for(int i = 0; i < ba.length; i++) {
           sb.append(hexValue[(ba[i] >> 4) & 0x0F]);
           sb.append(hexValue[ba[i] & 0x0F]);
        }
        return sb.toString();
    }
    private static byte[] dehexify(String s) {
        int l = s.length() / 2;
        byte[] res = new byte[l];
        for(int i = 0; i < l; i++) {
           res[i] = (byte)Integer.parseInt(s.substring(2*i, 2*i+2), 16);
        }
        return res;
    }
}
