Excerpt§
Discover the basics of Base64 encoding,decoding and how to use Kotlin’s built-in library for efficient encoding.
Base64 Basics§
Base64 is a method of representing arbitrary binary data using 64 characters. Since 2 to the power of 6 equals 64, each group of 6 bits can be represented by a printable character. Three bytes, or 24 bits, correspond to 4 Base64 groups, which means that three bytes can be represented by four printable characters.
Encoding§
To encode the original data, divide it into groups of three bytes, which gives 24 bits. Then, divide these 24 bits into four groups of 6 bits each. This will give you four numbers as indices, which can be used to look up the corresponding four characters in the Base64 table. These four characters form the encoded string.
Decoding§
To decode the encoded string, divide it into groups of four characters, which gives 16 bits. Then, divide these 16 bits into three groups of 8 bits each. This will give you three bytes, which can be concatenated to obtain the original data. Base64 encoding is commonly used for transmitting small amounts of binary data in situations such as URLs, cookies, and web pages.
Using Kotlin’s Built-in Base64 Library§
Base64 encoding is a common technique used to convert binary data into ASCII text format. The encoded data can then be easily transmitted through communication channels that support only ASCII characters. In Java, we can use the built-in Base64 class for encoding and decoding strings.
Encoding with Java’s Base64 Class§
To encode a string with Java’s Base64 class, we can use the getEncoder()
and encodeToString()
functions provided by the java.util.Base64
class. Here is an example:
1val originalString = "Hello, world!"
2val encodedString = Base64.getEncoder().encodeToString(originalString.toByteArray())
3println("Encoded string: $encodedString")
kotlin
1Encoded string: SGVsbG8sIHdvcmxkIQ==
text
In this example, we first define a string to be encoded (originalString
). Next, we use the getBytes()
function to convert the string into a byte array. Finally, we pass the byte array to the encodeToString()
function to get the encoded string.
The free Base64 Encode verification tool is as follows:§
Decoding with Java’s Base64 Class§
To decode a Base64-encoded string with Java’s Base64 class, we can use the getDecoder()
and decode()
functions provided by the java.util.Base64
class. Here is an example:
1val encodedString = "SGVsbG8sIHdvcmxkIQ=="
2val decodedBytes = Base64.getDecoder().decode(encodedString)
3val decodedString = String(decodedBytes)
4println("Decoded string: $decodedString")
kotlin
1Decoded string: Hello, world!
text
In this example, we first define a Base64-encoded string (encodedString
). Next, we use the decode()
function to decode the encoded string into a byte array. Finally, we convert the byte array back into a string representation to get the decoded string.