【问题标题】:Java - Why StringBuffer require base64 to get correct hex?Java - 为什么 StringBuffer 需要 base64 才能获得正确的十六进制?
【发布时间】:2018-06-06 11:21:05
【问题描述】:

例如这将得到正确的 'A' 十六进制值 0x41:

    StringBuffer strBuf = new StringBuffer();
    strBuf.append(toBase64("A".getBytes()));
    String ciphertext = strBuf.toString();
    byte[] encryted_bytes = ciphertext.getBytes();
    byte[] cipherBytes = fromBase64(new String(encryted_bytes));

    StringBuilder sb = new StringBuilder();
    for (byte b : cipherBytes) {
        sb.append(String.format("%02X ", b));
    }
    Log.d("hole", "hex:" + sb.toString());

但是没有base64,这会得到5B 42 40 33 33 64 62 35 61 30

    StringBuffer strBuf = new StringBuffer();
    strBuf.append(("A".getBytes()));
    String ciphertext = strBuf.toString();
    byte[] encryted_bytes = ciphertext.getBytes();
    byte[] cipherBytes = new String(encryted_bytes).getBytes();

    StringBuilder sb = new StringBuilder();
    for (byte b : cipherBytes) {
        sb.append(String.format("%02X ", b));
    }
    Log.d("hole", "hex:" + sb.toString());

base64的方法:

public static String toBase64(byte[] bytes) {
    return Base64.encodeToString(bytes, Base64.NO_WRAP);
}

public static byte[] fromBase64(String base64) {
    return Base64.decode(base64, Base64.NO_WRAP);
}

第二个代码生成5B 42 40 33 33 64 62 35 61 30的步骤是什么?以及base64如何使它生成正确的十六进制?

【问题讨论】:

    标签: java arrays base64 byte stringbuffer


    【解决方案1】:

    这里的关键是没有StringBuffer.append(byte[])方法。

    那么当使用byte[]-参数调用append 时会发生什么? JVM 选择下一个最佳匹配,即append(Object),每个 javadoc 执行以下操作:

    整体效果就像是通过 String.valueOf(Object) 方法将参数转换为字符串,然后将该字符串的字符附加到该字符序列中。

    所以它附加了byte[] 的字符串表示,看起来像

    [B@33db5a0 
    

    第二种方法通过使用 String 字节数组的 Base64 表示来纠正这一点,因此选择的方法是 append(String)

    作为一般规则:始终注意您在哪里使用bytes 以及在哪里使用charString,并且永远不要对字节数组使用字符串操作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-01-14
      • 1970-01-01
      • 2022-01-02
      • 1970-01-01
      • 2020-05-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多