Skip to content
DeveloperMemos

How to Convert to and from Base64 in Kotlin

Kotlin, Base64, Encoding1 min read

Base64 is a binary-to-text encoding scheme that is commonly used to represent arbitrary binary data in a text format. This is useful when you need to transfer binary data, such as images or other files, over a network or other communication channel that is designed to handle only text data.

In Kotlin, you can easily convert data to and from Base64 using the Base64 class from the standard library. This class provides static methods for encoding and decoding data in Base64 format.

Here's an example of how to encode a string in Base64 format:

1import java.util.Base64
2
3val input = "Hello, world!"
4val encoded = Base64.getEncoder().encodeToString(input.toByteArray())
5println(encoded) // Output: "SGVsbG8sIHdvcmxkIQ=="

The getEncoder() method returns a Base64.Encoder object that you can use to encode data. The encodeToString() method takes the input data (in this case, a ByteArray containing the bytes of the input string) and returns the Base64-encoded version of the data as a String.

To decode a Base64-encoded string, you can use the getDecoder() method to get a Base64.Decoder object, and then call the decode() method on that object:

1val decoded = Base64.getDecoder().decode(encoded)
2println(String(decoded)) // Output: "Hello, world!"

The decode() method takes a String containing the Base64-encoded data and returns a ByteArray containing the decoded data. In this example, we convert the ByteArray to a String using the String class's constructor, which takes a ByteArray as its argument.

In addition to encoding and decoding strings, the Base64 class also provides methods for encoding and decoding other types of data, such as ByteArrays, InputStreams, and OutputStreams. You can find more information about these methods in the Android documentation.

In summary, the Base64 class in Kotlin makes it easy to convert data to and from Base64 format. This can be useful when you need to transfer binary data over a network or other communication channel that is designed to handle only text data.