Her er noget kode.
Det er kun encode ikke decode.
Og der er fejl i en af casene (alle fra row 0x00 eller en anden row).
Sig til hvis det er værd at arbejde lidt videre på dette:
public class RACE {
private static byte[] compress(char[] c) {
boolean allhighsame = true;
int ff = 0;
for(int i = 1; i < c.length; i++) {
if((c[i] >> 8) != (c[0] >> 8)) {
allhighsame = false;
}
if(((c[i] & 0xFF00) == 0xFF00) || ((c[i] & 0xFF) == 0xFF)) {
ff++;
}
}
if(allhighsame) {
byte[] res = new byte[c.length + 1 + ff];
res[0] = (byte)(c[0] >> 8);
int ix = 1;
for(int i = 0; i < c.length; i++) {
res[ix] = (byte)(c[i] & 0xFF);
if(res[ix] == (byte)0xFF) {
res[ix + 1] = (byte)0x99;
ix++;
}
ix++;
}
return res;
} else {
byte[] res = new byte[c.length * 2 + 1];
res[0] = (byte)0xD8;
for(int i = 0; i < c.length; i++) {
res[2 * i + 1] = (byte)(c[i] >> 8);
res[2 * i + 2] = (byte)(c[i] & 0xFF);
}
return res;
}
}
private static final char[] b32 =
{ 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',
'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p',
'q', 'r', 's', 't', 'u', 'v', 'w', 'x',
'y', 'z', '2', '3', '4', '5', '6', '7' };
private static char[] base32encode(byte[] b) {
int len = (b.length * 8 - 1) / 5 + 1;
char[] res = new char[len];
short acc = 0;
int bits = 0;
int ix = 0;
for(int i = 0; i < len; i++) {
if(bits < 5) {
acc |= (((ix < b.length) ? b[ix] : 0) << (8 - bits));
bits += 8;
ix++;
}
res[i] = b32[(acc & 0xF800) >> 11];
acc <<= 5;
bits -= 5;
}
return res;
}
private static char[] decompress(byte[] b) {
return null;
}
private static byte[] base32decode(char[] c) {
return null;
}
private static String encode(String s) {
return "bq--" + new String(base32encode(compress(s.toCharArray())));
}
private static String decode(String s) {
return new String(decompress(base32decode(s.substring(4).toCharArray())));
}
private static char hexdigit[] =
{ '0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
private static String toHex(byte[] ba) {
StringBuffer sb = new StringBuffer("");
for (int i = 0; i < ba.length; i++) {
sb.append(hexdigit[(ba[i] >> 4) & 0x0F]);
sb.append(hexdigit[ba[i] & 0x0F]);
}
return sb.toString();
}
public static void main(String[] args) {
// test compress
char[] c1 = { '\u012D', '\u0111', '\u014B' };
byte[] b1 = compress(c1);
System.out.println("012D114B=" + toHex(b1));
char[] c2 = { '\u012D', '\u00E0', '\u014B' };
byte[] b2 = compress(c2);
System.out.println("012DFFE04B=" + toHex(b2));
char[] c3 = { '\u1290', '\u12FF', '\u120C' };
byte[] b3 = compress(c3);
System.out.println("1290FF990C=" + toHex(b3));
char[] c4 = { '\u012D', '\u00E0', '\u24D3' };
byte[] b4 = compress(c4);
System.out.println("D8012D00E024D3=" + toHex(b4));
// test base32 encode
byte[] b5 = { (byte)0x3a, (byte)0x27, (byte)0x0f, (byte)0x93 };
char[] c5 = base32encode(b5);
System.out.println("hitq7ey=" + new String(c5));
// test danish
System.out.println(encode("ÆØÅæøå"));
}
}