mass rename and rebranding from xwt to ibex - fixed to use ixt files
[org.ibex.core.git] / src / org / ibex / util / PackBytesIntoString.java
diff --git a/src/org/ibex/util/PackBytesIntoString.java b/src/org/ibex/util/PackBytesIntoString.java
new file mode 100644 (file)
index 0000000..1e07e86
--- /dev/null
@@ -0,0 +1,47 @@
+// Copyright (C) 2003 Adam Megacz <adam@ibex.org> all rights reserved.
+//
+// You may modify, copy, and redistribute this code under the terms of
+// the GNU Library Public License version 2.1, with the exception of
+// the portion of clause 6a after the semicolon (aka the "obnoxious
+// relink clause")
+
+package org.ibex.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;
+    }
+}