licensing update to APSL 2.0
[org.ibex.util.git] / src / org / ibex / util / PackBytesIntoString.java
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.
4
5 package org.ibex.util;
6
7 /** packs 8-bit bytes into a String of 7-bit chars (to avoid the UTF-8 non-ASCII penalty) */
8 public class PackBytesIntoString {
9
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) {
14             long l = 0;
15             for(int j=6; j>=0; j--) {
16                 l <<= 8;
17                 l |= (b[i + j] & 0xff);
18             }
19             for(int j=0; j<8; j++) {
20                 ret.append((char)(l & 0x7f));
21                 l >>= 7;
22             }
23         }
24         return ret.toString();
25     }
26
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) {
31             long l = 0;
32             for(int j=7; j>=0; j--) {
33                 l <<= 7;
34                 l |= (s.charAt(i + j) & 0x7fL);
35             }
36             for(int j=0; j<7; j++) {
37                 ret[(i / 8) * 7 + j] = (byte)(l & 0xff);
38                 l >>= 8;
39             }
40         }
41         return ret;
42     }
43 }
44