1 // Copyright 2000-2005 the Contributors, as shown in the revision logs.
2 // Licensed under the Apache Public Source License 2.0 ("the License").
3 // You may not use this file except in compliance with the License.
7 /** packs 8-bit bytes into a String of 7-bit chars (to avoid the UTF-8 non-ASCII penalty) */
8 public class PackBytesIntoString {
10 public static String pack(byte[] b, int off, int len) throws IllegalArgumentException {
11 if (len % 7 != 0) throw new IllegalArgumentException("len must be a multiple of 7");
12 StringBuffer ret = new StringBuffer();
13 for(int i=off; i<off+len; i += 7) {
15 for(int j=6; j>=0; j--) {
17 l |= (b[i + j] & 0xff);
19 for(int j=0; j<8; j++) {
20 ret.append((char)(l & 0x7f));
24 return ret.toString();
27 public static byte[] unpack(String s) throws IllegalArgumentException {
28 if (s.length() % 8 != 0) throw new IllegalArgumentException("string length must be a multiple of 8");
29 byte[] ret = new byte[(s.length() / 8) * 7];
30 for(int i=0; i<s.length(); i += 8) {
32 for(int j=7; j>=0; j--) {
34 l |= (s.charAt(i + j) & 0x7fL);
36 for(int j=0; j<7; j++) {
37 ret[(i / 8) * 7 + j] = (byte)(l & 0xff);