initial checkin
[org.ibex.nanogoat.git] / src / org / ibex / util / PackBytesIntoString.java
1 // Copyright (C) 2003 Adam Megacz <adam@ibex.org> all rights reserved.
2 //
3 // You may modify, copy, and redistribute this code under the terms of
4 // the GNU Library Public License version 2.1, with the exception of
5 // the portion of clause 6a after the semicolon (aka the "obnoxious
6 // relink clause")
7
8 package org.ibex.util;
9
10 /** packs 8-bit bytes into a String of 7-bit chars (to avoid the UTF-8 non-ASCII penalty) */
11 public class PackBytesIntoString {
12
13     public static String pack(byte[] b, int off, int len) throws IllegalArgumentException {
14         if (len % 7 != 0) throw new IllegalArgumentException("len must be a multiple of 7");
15         StringBuffer ret = new StringBuffer();
16         for(int i=off; i<off+len; i += 7) {
17             long l = 0;
18             for(int j=6; j>=0; j--) {
19                 l <<= 8;
20                 l |= (b[i + j] & 0xff);
21             }
22             for(int j=0; j<8; j++) {
23                 ret.append((char)(l & 0x7f));
24                 l >>= 7;
25             }
26         }
27         return ret.toString();
28     }
29
30     public static byte[] unpack(String s) throws IllegalArgumentException {
31         if (s.length() % 8 != 0) throw new IllegalArgumentException("string length must be a multiple of 8");
32         byte[] ret = new byte[(s.length() / 8) * 7];
33         for(int i=0; i<s.length(); i += 8) {
34             long l = 0;
35             for(int j=7; j>=0; j--) {
36                 l <<= 7;
37                 l |= (s.charAt(i + j) & 0x7fL);
38             }
39             for(int j=0; j<7; j++) {
40                 ret[(i / 8) * 7 + j] = (byte)(l & 0xff);
41                 l >>= 8;
42             }
43         }
44         return ret;
45     }
46 }
47