public static String encode(byte[] a){
  if (a == null || a.length == 0) {
    return "x";
  }
  int[] cnt=new int[256];
  for (int i=0; i < a.length; i++) {
    cnt[a[i] & 0xff]++;
  }
  int shift=1;
  int nEscapes=a.length;
  for (int i=1; i < 256; i++) {
    if (i == '\'') {
      continue;
    }
    int sum=cnt[i] + cnt[(i + 1) & 0xff] + cnt[(i + '\'') & 0xff];
    if (sum < nEscapes) {
      nEscapes=sum;
      shift=i;
      if (nEscapes == 0) {
        break;
      }
    }
  }
  int outLen=a.length + nEscapes + 1;
  StringBuffer out=new StringBuffer(outLen);
  out.append((char)shift);
  for (int i=0; i < a.length; i++) {
    char c=(char)((a[i] - shift) & 0xff);
    if (c == 0) {
      out.append((char)1);
      out.append((char)1);
    }
 else     if (c == 1) {
      out.append((char)1);
      out.append((char)2);
    }
 else     if (c == '\'') {
      out.append((char)1);
      out.append((char)3);
    }
 else {
      out.append(c);
    }
  }
  return out.toString();
}

public static String encode ( byte [ ] a ) { if ( a == null || a . length == 0 ) { return "x" ; } int [ ] cnt = new int [ 256 ] ; for ( int i = 0 ; i < a . length ; i ++ ) { cnt [ a [ i ] & 0xff ] ++ ; } int shift = 1 ; int nEscapes = a . length ; for ( int i = 1 ; i < 256 ; i ++ ) { if ( i == '\'' ) { continue ; } int sum = cnt [ i ] + cnt [ ( i + 1 ) & 0xff ] + cnt [ ( i + '\'' ) & 0xff ] ; if ( sum < nEscapes ) { nEscapes = sum ; shift = i ; if ( nEscapes == 0 ) { break ; } } } int outLen = a . length + nEscapes + 1 ; StringBuffer out = new StringBuffer ( outLen ) ; out . append ( ( char ) shift ) ; for ( int i = 0 ; i < a . length ; i ++ ) { char c = ( char ) ( ( a [ i ] - shift ) & 0xff ) ; if ( c == 0 ) { out . append ( ( char ) 1 ) ; out . append ( ( char ) 1 ) ; } else if ( c == 1 ) { out . append ( ( char ) 1 ) ; out . append ( ( char ) 2 ) ; } else if ( c == '\'' ) { out . append ( ( char ) 1 ) ; out . append ( ( char ) 3 ) ; } else { out . append ( c ) ; } } return out . toString ( ) ; }
encodes the given byte array into a string that can be used by the sqlite database . the database cannot handle null ( 0x00 ) and the character ' \ ' ' ( 0x27 ) . the encoding consists of escaping these characters with a reserved character ( 0x01 ) . the escaping is applied after determining and applying a shift that minimizes the number of escapes required . with this encoding the data of original size n is increased to a maximum of 1 + ( n * 257 ) / 254 . for sufficiently large n the overhead is thus less than 1 . 2 % .
