【问题标题】:Method that converts array of integers into base64 in JavaJava中将整数数组转换为base64的方法
【发布时间】:2018-11-04 15:23:59
【问题描述】:

方法String toBase64(Integer[] decimalCh)接受一个从0到63的整数数组,并根据base64表返回一个编码字符串:

private static final char b64[] = {
      'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
      'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
      'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
      'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',
      'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
      'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
      'w', 'x', 'y', 'z', '0', '1', '2', '3',
      '4', '5', '6', '7', '8', '9', '+', '/'
  };

我想实现方法,让每个整数都匹配表中的索引字符,例如:

Integer[] decChar = {37, 62, 37, 43, 0}
String result = toBase64(decChar);

输出:l+lrA

我试图通过嵌套循环来实现它,但它似乎不是一个准确的方法

public static String toBase64(Integer[] decimalCh) {
      String result = "";
      for (int i = 0; i < decimalCh.length; i++) {
          for(int j = 0; j < b64.length; j++) {   
                  result += b64[j];

          }
      }
    return result; 

【问题讨论】:

标签: java base64 decode encode


【解决方案1】:

没有理由遍历b64 表。只需在decimalCh 中查找每个整数值的条目。此外,您应该使用 StringBuilder 而不是每次循环都附加到字符串本身。像这样的东西应该可以工作:

public static String toBase64(Integer[] decimalCh) {
    StringBuilder result = new StringBuilder();
    for (Integer i : decimalCh) {
        result.append(b64[i]);
    }
    return result.toString();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-05-21
    • 2011-04-13
    • 1970-01-01
    • 1970-01-01
    • 2011-01-25
    • 2010-12-28
    相关资源
    最近更新 更多