0

I'm writing a REST client from a C# usage example. Now i need to convert a string in the proper format but can't find the equivalent method on Java.

original:

string Credentials = Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes(string);

At this point I've done this:

String Credentials = new String(DatatypeConverter.parseBase64Binary(String)); 

but i still need the ASCII conversion and I'm not sure that the things I've fount will work fine, like: Convert character to ASCII numeric value in java

any clues?

Thank you.

Community
  • 1
  • 1
Freddy
  • 15
  • 9
  • 1
    Can you clarify whether you want to produce Base64 from ASCII, like in the C# example, or ASCII from Base64, like your usage of parseBase64Binary suggests? – Aaron Feb 10 '16 at 13:50
  • 2
    Fundamentally, it's unclear what you're trying to achieve here. Please provide more details. – Jon Skeet Feb 10 '16 at 13:51
  • I'm just trying to achieve to have the same content in the Credentials variable. I thought was pretty clear, sorry. My code still needs to produce a ASCII encoding of the String variable that then will be converted in Base64. Am I right? – Freddy Feb 10 '16 at 14:00
  • 1
    Your question is confusing because "ASCII conversion" isn't really valid terminology. I think you are asking how to convert a String to bytes, using the ASCII encoding, in which case the answer is `someString.getBytes(StandardCharsets.US_ASCII)`. *Caution:* If your String contains characters whose numeric codepoint is larger than 127, that information will be obliterated. For that reason, you should use `StandardCharsets.UTF_8`, which will accommodate every possible character value. – VGR Feb 10 '16 at 15:36
  • I actually didn't need the ASCII representation (am I saying it right? :D) of the string. It is something that who made the c# example, needed in that case. I was finally able to use the ws by using Aaron's advice and the java8 method. thanks! :) – Freddy Feb 11 '16 at 10:33

1 Answers1

0

If you're using java 8 you should take a look at its new Base64 class. It will provide you with a Base64.Encoder whose encodeToString(byte[] src) method accepts a byte array and return a base64 encoded String.

String base64 = Base64.getEncoder().encodeToString("I'm a String".getBytes());
System.out.println(base64); // prints SSdtIGEgU3RyaW5n
Aaron
  • 24,009
  • 2
  • 33
  • 57
  • There should be some way to specify ASCII ? – Dave Doknjas Feb 10 '16 at 16:10
  • No there shouldn't, and I really don't see why C# would require that. `String.getBytes` provides the actual bytes, whether the string is ASCII or unicode, and Base64 encodes theses bytes to text. It's when you decode the Base64 bytes that you have to say whether the encoded bytes are ASCII or unicode or whatever – Aaron Feb 10 '16 at 16:52