Why those calls to base64 classes return different results?

My code:

private static String convertToBase64(String string)
{
    final byte[] encodeBase64 =
            org.apache.commons.codec.binary.Base64.encodeBase64(string
                    .getBytes());
    System.out.println(Hex.encodeHexString(encodeBase64));

    final byte[] data = string.getBytes();
    final String encoded =
            javax.xml.bind.DatatypeConverter.printBase64Binary(data);
    System.out.println(encoded);

    return encoded;
}

Now I'm calling it: convertToBase64("stackoverflow"); and get following result:

6333526859327476646d56795a6d787664773d3d
c3RhY2tvdmVyZmxvdw==

Why I get different results?

Answers


I think Hex.encodeHexString will encode your String to hexcode, and the second one is a normal String


From the API doc of Base64.encodeBase64():

byte[] containing Base64 characters in their UTF-8 representation.

So instead

System.out.println(Hex.encodeHexString(encodeBase64));

you should write

System.out.println(new String(encodeBase64, "UTF-8"));

BTW: You should never use the String.getBytes() version without explicit encoding, because the result depends on the default platform encoding (for Windows this is usually "Cp1252" and Linux "UTF-8").


Need Your Help

boost/geometry.hpp: No such file or directory

ubuntu boost compilation ubuntu-12.04 boost-geometry

I am trying to compile a c-extension for ruby. It requires the boost libraries.

Noobish query, but how do i get the actual .exe file of my finished Delphi Application

delphi delphi-xe4

so basically i have finished a project and want to create the .exe file for transporting to another computer for testing purposes.