hawx
hawx

Reputation: 1669

Convert Base64 String to Byte Value String in Java

I have a Base64 String, which is 'AAAC', which in binary is equivalent to 3 bytes (00000000 00000000 00000010).

I would like to convert 'AAAC' to a ASCII Hex Byte String to output something like '000002'.

I have tried below.

byte[] test = Base64.decode(data.getBytes());
StringBuilder sb = new StringBuilder();
for (byte b : test) {
    sb.append(String.format("%02X ", b));
}
System.out.println(sb.toString()); 
//Output: 00 00 02 

This works, but is there a more effient way to do this?

Any help would be appreciated. Thanks in advance.

Upvotes: 1

Views: 807

Answers (2)

Louis Wasserman
Louis Wasserman

Reputation: 198103

With the Guava library, this might look something like

BaseEncoding.base16().toUpperCase().withSeparator(" ", 2)
  .encode(BaseEncoding.base64().decode(data));

Upvotes: 1

Duncan Jones
Duncan Jones

Reputation: 69339

You could use the DatatypeConverter class for this:

String result =
    DatatypeConverter.printHexBinary(DatatypeConverter
        .parseBase64Binary("AAAC"));

System.out.println(result);

Prints: 000002

Upvotes: 2

Related Questions