编码/解码字符串和特殊字符到字节数组

时间:2009-12-09 13:41:10

标签: java encoding bytearray decode

我要求将3个字符的字符串(总是字母表)编码为2个整数的2字节[]数组。 这样做是为了节省空间和性能的原因。

现在要求发生了一些变化。 String的长度可变。它的长度为3(如上所示)或长度为4,开头时将有1个特殊字符。特殊字符是固定的,即如果我们选择@它将永远是@并始终在开头。所以我们确定如果String的长度为3,它将只有字母表,如果长度为4,则第一个字符将始终为'@',后跟3个字母

所以我可以使用

charsAsNumbers[0] = (byte) (locationChars[0] - '@');

而不是

charsAsNumbers[0] = (byte) (chars[0] - 'A');

我仍然可以将3或4个字符编码为2字节数组并将其解码回来吗?如果是这样,怎么样?

5 个答案:

答案 0 :(得分:2)

不是直接答案,但这是我如何进行编码:

   public static byte[] encode(String s) {
      int code = s.charAt(0) - 'A' + (32 * (s.charAt(1) - 'A' + 32 * (s.charAt(2) - 'A')));
      byte[] encoded = { (byte) ((code >>> 8) & 255), (byte) (code & 255) };
      return encoded;
   }

第一行使用Horner的Schema将每个字符的5位算术数组成一个整数。如果你的任何输入字符超出范围[A-`],它将会非常失败。

第二行从整数的前导和尾随字节组装一个2字节数组。

解码可以以类似的方式完成,步骤相反。


用代码

更新(把我的脚放在嘴边,或类似的东西):

public class TequilaGuy {

   public static final char SPECIAL_CHAR = '@';

   public static byte[] encode(String s) {
      int special = (s.length() == 4) ? 1 : 0;
      int code = s.charAt(2 + special) - 'A' + (32 * (s.charAt(1 + special) - 'A' + 32 * (s.charAt(0 + special) - 'A' + 32 * special)));
      byte[] encoded = { (byte) ((code >>> 8) & 255), (byte) (code & 255) };
      return encoded;
   }

   public static String decode(byte[] b) {
      int code = 256 * ((b[0] < 0) ? (b[0] + 256) : b[0]) + ((b[1] < 0) ? (b[1] + 256) : b[1]);
      int special = (code >= 0x8000) ? 1 : 0;
      char[] chrs = { SPECIAL_CHAR, '\0', '\0', '\0' };
      for (int ptr=3; ptr>0; ptr--) {
         chrs[ptr] = (char) ('A' + (code & 31));
         code >>>= 5;
      }
      return (special == 1) ? String.valueOf(chrs) : String.valueOf(chrs, 1, 3);
   }

   public static void testEncode() {
      for (int spcl=0; spcl<2; spcl++) {
         for (char c1='A'; c1<='Z'; c1++) {
            for (char c2='A'; c2<='Z'; c2++) {
               for (char c3='A'; c3<='Z'; c3++) {
                  String s = ((spcl == 0) ? "" : String.valueOf(SPECIAL_CHAR)) + c1 + c2 + c3;
                  byte[] cod = encode(s);
                  String dec = decode(cod);
                  System.out.format("%4s : %02X%02X : %s\n", s, cod[0], cod[1], dec);
               }
            }
         }
      }
   }

   public static void main(String[] args) {
      testEncode();
   }

}

答案 1 :(得分:1)

在您的字母表中,您只使用输出的16个可用位中的15位。因此,如果字符串长度为4,则可以设置MSB(最高位),因为特殊字符是固定的。

另一种选择是使用翻译表。只需创建一个包含所有有效字符的字符串:

String valid = "@ABCDEFGHIJKLMNOPQRSTUVWXYZ";

此字符串中的字符索引是输出中的编码。现在创建两个数组:

byte encode[] = new byte[256];
char decode[] = new char[valid.length ()];
for (int i=0; i<valid.length(); i++) {
    char c = valid.charAt(i);
    encode[c] = i;
    decode[i] = c;
}

现在,您可以查找数组中每个方向的值,并按任意顺序添加您喜欢的任何字符。

答案 2 :(得分:1)

是的, 可以对额外的信息进行编码,同时保持3个字符值的先前编码。但是由于你的原始编码没有在输出集中留下漂亮的大量自由数字,因此通过添加额外字符引入的附加字符串集的映射不能不会有点不连续。

因此,我认为很难提出处理这些不连续性的映射函数,而不是既笨拙又慢。我的结论是基于表的映射是唯一合理的解决方案。

我懒得重新设计您的映射代码,所以我把它合并到了我的表初始化代码中;这也消除了很多翻译错误的机会:)我的encode()方法就是我所说的OldEncoder.encode()

我运行了一个小型测试程序,以验证NewEncoder.encode()是否提供与OldEncoder.encode()相同的值,并且还能够使用前导第4个字符对字符串进行编码。 NewEncoder.encode()不关心字符是什么,它取决于字符串长度;对于decode(),可以使用PREFIX_CHAR定义使用的字符。我还要检查前缀字符串的字节数组值是否与非前缀字符串的字节数组值重复;最后,编码的前缀字符串确实可以转换回相同的前缀字符串。

package tequilaguy;


public class NewConverter {

   private static final String[] b2s = new String[0x10000];
   private static final int[] s2b = new int[0x10000];
   static { 
      createb2s();
      creates2b();
   }

   /**
    * Create the "byte to string" conversion table.
    */
   private static void createb2s() {
      // Fill 17576 elements of the array with b -> s equivalents.
      // index is the combined byte value of the old encode fn; 
      // value is the String (3 chars). 
      for (char a='A'; a<='Z'; a++) {
         for (char b='A'; b<='Z'; b++) {
            for (char c='A'; c<='Z'; c++) {
               String str = new String(new char[] { a, b, c});
               byte[] enc = OldConverter.encode(str);
               int index = ((enc[0] & 0xFF) << 8) | (enc[1] & 0xFF);
               b2s[index] = str;
               // int value = 676 * a + 26 * b + c - ((676 + 26 + 1) * 'A'); // 45695;
               // System.out.format("%s : %02X%02X = %04x / %04x %n", str, enc[0], enc[1], index, value);
            }
         }
      }
      // Fill 17576 elements of the array with b -> @s equivalents.
      // index is the next free (= not null) array index;
      // value = the String (@ + 3 chars)
      int freep = 0;
      for (char a='A'; a<='Z'; a++) {
         for (char b='A'; b<='Z'; b++) {
            for (char c='A'; c<='Z'; c++) {
               String str = "@" + new String(new char[] { a, b, c});
               while (b2s[freep] != null) freep++;
               b2s[freep] = str;
               // int value = 676 * a + 26 * b + c - ((676 + 26 + 1) * 'A') + (26 * 26 * 26);
               // System.out.format("%s : %02X%02X = %04x / %04x %n", str, 0, 0, freep, value);
            }
         }
      }
   }

   /**
    * Create the "string to byte" conversion table.
    * Done by inverting the "byte to string" table.
    */
   private static void creates2b() {
      for (int b=0; b<0x10000; b++) {
         String s = b2s[b];
         if (s != null) {
            int sval;
            if (s.length() == 3) {
               sval = 676 * s.charAt(0) + 26 * s.charAt(1) + s.charAt(2) - ((676 + 26 + 1) * 'A');
            } else {
               sval = 676 * s.charAt(1) + 26 * s.charAt(2) + s.charAt(3) - ((676 + 26 + 1) * 'A') + (26 * 26 * 26);
            }
            s2b[sval] = b;
         }
      }
   }

   public static byte[] encode(String str) {
      int sval;
      if (str.length() == 3) {
         sval = 676 * str.charAt(0) + 26 * str.charAt(1) + str.charAt(2) - ((676 + 26 + 1) * 'A');
      } else {
         sval = 676 * str.charAt(1) + 26 * str.charAt(2) + str.charAt(3) - ((676 + 26 + 1) * 'A') + (26 * 26 * 26);
      }
      int bval = s2b[sval];
      return new byte[] { (byte) (bval >> 8), (byte) (bval & 0xFF) };
   }

   public static String decode(byte[] b) {
      int bval = ((b[0] & 0xFF) << 8) | (b[1] & 0xFF);
      return b2s[bval];
   }

}

我在代码中留下了一些错综复杂的常量表达式,尤其是26次幂的东西。否则,代码看起来非常神秘。您可以保留原样而不会丢失性能,因为编译器会像Kleenexes一样将它们折叠起来。


<强>更新

随着X-mas的恐怖逼近,我将在路上待一段时间。我希望你能及时找到这个答案和代码,以便充分利用它。为了支持我将在我的小测试程序中投入的努力。它不会直接检查内容,而是以所有重要方式打印出转换结果,并允许您通过眼睛和手来检查它们。我摆弄了我的代码(一旦我得到了基本的想法,就进行了小调整),直到一切看起来都不错。您可能希望更加机械和详尽地进行测试。

package tequilaguy;

public class ConverterHarness {

//   private static void runOldEncoder() {
//      for (char a='A'; a<='Z'; a++) {
//         for (char b='A'; b<='Z'; b++) {
//            for (char c='A'; c<='Z'; c++) {
//               String str = new String(new char[] { a, b, c});
//               byte[] enc = OldConverter.encode(str);
//               System.out.format("%s : %02X%02X%n", str, enc[0], enc[1]);
//            }
//         }
//      }
//   }

   private static void testNewConverter() {
      for (char a='A'; a<='Z'; a++) {
         for (char b='A'; b<='Z'; b++) {
            for (char c='A'; c<='Z'; c++) {
               String str = new String(new char[] { a, b, c});
               byte[] oldEnc = OldConverter.encode(str);
               byte[] newEnc = NewConverter.encode(str);
               byte[] newEnc2 = NewConverter.encode("@" + str);
               System.out.format("%s : %02X%02X %02X%02X %02X%02X %s %s %n", 
                     str, oldEnc[0], oldEnc[1], newEnc[0], newEnc[1], newEnc2[0], newEnc2[1],
                     NewConverter.decode(newEnc), NewConverter.decode(newEnc2));
            }
         }
      }
   }
   public static void main(String[] args) {
      testNewConverter();
   }

}

答案 3 :(得分:0)

如果您只是使用java.nio.charset.CharsetEncoder类将字符转换为字节,您会发现这更容易。它甚至可以用于ASCII以外的字符。对于相同的基本效果,即使String.getBytes代码也会少得多。

答案 4 :(得分:0)

如果修复了“特殊字符”并且您始终知道4个字符的字符串以此特殊字符开头,那么字符本身不会提供有用的信息。

如果字符串的长度为3个字符,那么就按照之前的做法进行操作;如果它是4个字符,则在String的子字符串上运行旧算法,从第2个字符开始。

我是在想太简单还是你想得太辛苦了?