2003/11/14 07:47:05
authormegacz <megacz@xwt.org>
Fri, 30 Jan 2004 07:41:22 +0000 (07:41 +0000)
committermegacz <megacz@xwt.org>
Fri, 30 Jan 2004 07:41:22 +0000 (07:41 +0000)
darcs-hash:20040130074122-2ba56-f8269657aaebf8e89190fa39cf54621b80270220.gz

src/org/xwt/util/PackBytesIntoString.java [new file with mode: 0644]

diff --git a/src/org/xwt/util/PackBytesIntoString.java b/src/org/xwt/util/PackBytesIntoString.java
new file mode 100644 (file)
index 0000000..6579f7e
--- /dev/null
@@ -0,0 +1,42 @@
+package org.xwt.util;
+import java.io.*;
+import java.util.*;
+
+/** packs 8-bit bytes into a String of 7-bit chars (to avoid the UTF-8 non-ASCII penalty) */
+public class PackBytesIntoString {
+
+    public static String pack(byte[] b, int off, int len) throws IllegalArgumentException {
+        if (len % 7 != 0) throw new IllegalArgumentException("len must be a multiple of 7");
+        StringBuffer ret = new StringBuffer();
+        for(int i=off; i<off+len; i += 7) {
+            long l = 0;
+            for(int j=6; j>=0; j--) {
+                l <<= 8;
+                l |= (b[i + j] & 0xff);
+            }
+            for(int j=0; j<8; j++) {
+                ret.append((char)(l & 0x7f));
+                l >>= 7;
+            }
+        }
+        return ret.toString();
+    }
+
+    public static byte[] unpack(String s) throws IllegalArgumentException {
+        if (s.length() % 8 != 0) throw new IllegalArgumentException("string length must be a multiple of 8");
+        byte[] ret = new byte[(s.length() / 8) * 7];
+        for(int i=0; i<s.length(); i += 8) {
+            long l = 0;
+            for(int j=7; j>=0; j--) {
+                l <<= 7;
+                l |= (s.charAt(i + j) & 0x7fL);
+            }
+            for(int j=0; j<7; j++) {
+                ret[(i / 8) * 7 + j] = (byte)(l & 0xff);
+                l >>= 8;
+            }
+        }
+        return ret;
+    }
+}