Home » Android » java – android.util.Base64 encode/decode flags parameter

java – android.util.Base64 encode/decode flags parameter

Posted by: admin May 14, 2020 Leave a comment

Questions:

According to the Javadoc, android.util.Base64.decode() takes two parameters: the text, and “flags”. These flags are in int form and (I quote):

flags controls certain features of the decoded output. Pass DEFAULT to decode standard Base64.

First off, thanks to whomever decided to write a vague Javadoc. I see that Base64 has some enumeration strings, and in practice, we have been using Base64.NO_WRAP as our flag. In this particular instance, however, we need to employ two flags: NO_WRAP, and URL_SAFE.

How do we specify both flags? We tried separating them with a pipe (‘|’), and that didn’t do it.

import android.util.Base64;
public class Foo {
    public static void main(String[] args) {
        String urlSafeBase64EncodedString = getUrlSafeBase64EncodedString();
        int flags = ????????; //Need both Base64.NO_WRAP and Base64.URL_SAFE
        String decodedString = Base64.decode(urlSafeBase64EncodedString, flags);
    }
}

Thanks for your time.

How to&Answers:

int flags passed to functions are usually defined to be bitwise ORed to achieve a combined effect.

You can usually tell by looking at the constant values, they would go 0 1 2 4 8 16 ..

As for your question you can use the following for your flag definition:

int flags = Base64.NO_WRAP | Base64.URL_SAFE;

Answer:

For kotlin you can use

val flag = Base64.URL_SAFE or Base64.NO_WRAP