5 /** packs 8-bit bytes into a String of 7-bit chars (to avoid the UTF-8 non-ASCII penalty) */
6 public class PackBytesIntoString {
8 public static String pack(byte[] b, int off, int len) throws IllegalArgumentException {
9 if (len % 7 != 0) throw new IllegalArgumentException("len must be a multiple of 7");
10 StringBuffer ret = new StringBuffer();
11 for(int i=off; i<off+len; i += 7) {
13 for(int j=6; j>=0; j--) {
15 l |= (b[i + j] & 0xff);
17 for(int j=0; j<8; j++) {
18 ret.append((char)(l & 0x7f));
22 return ret.toString();
25 public static byte[] unpack(String s) throws IllegalArgumentException {
26 if (s.length() % 8 != 0) throw new IllegalArgumentException("string length must be a multiple of 8");
27 byte[] ret = new byte[(s.length() / 8) * 7];
28 for(int i=0; i<s.length(); i += 8) {
30 for(int j=7; j>=0; j--) {
32 l |= (s.charAt(i + j) & 0x7fL);
34 for(int j=0; j<7; j++) {
35 ret[(i / 8) * 7 + j] = (byte)(l & 0xff);