string pack and unpack
Hi, i齧 having trouble trying to write a methode to unpack a string packed with the following methode.
can some one tell me how to write the unpack methode ?
thanks.
public String pack(String s) {
byte[] a = new byte[16];
//If the string is an odd length then pack with an F
if ( s.length() % 2 == 1 ) {
s = (char) 0xFF + s ;
}
//Now pack each pair of bytes into the array
for ( int i = 0, j = 0 ; i < s.length() ; i += 2, j++ ) {
a[j] = (byte) ( ( (s.charAt(i) & 0x0F) << 4 ) +
(s.charAt(i+1) & 0x0F) ) ;
}
return new String(A);
}
[652 byte] By [
EMdYa] at [2007-9-28 3:32:06]

.. I would like to try and help but don't know exactly what you are asking. Do you want a method with the signature, public String unpack(String encodedString)? Are all of the Strings that you encode of length 16 characters? If not then information is going to be lost and the outputted String from the unpack method will be unreliable.
Please let me know and I will try to help.
You need know the assumptions about the content of the original string. A packing algorithm like the one you describe might be used to pack a numeric string into an array of bytes. In that case, you assume that the original string consisted of nothing but ASCII digits, and you can recover the string with the following method:
public String unpack(String a) {
byte [] b = a.getBytes();
StringBuffer buff = new StringBuffer(b.length * 2);
for (int i = 0; i < b.length; i++) {
buff.append((char)(0x30 | ((b[i] & 0xf0) >> 4)));
buff.append((char)(0x30 | (b[i] & 0x0f)));
}
// If the first char was a pad char, then remove it
if (buff.charAt(0) == (char)0x3f)
return buff.substring(1);
return buff.toString();
}
> A packing algorithm like the one you
> describe might be used to pack a numeric string into
> an array of bytes.
As I said before, a string does not contain bytes. It contains characters.
And the relevance of that is that characters in a string get there by being "encoded". And that is seldom a good thing for bytes.