Last active
September 15, 2018 16:53
-
-
Save NicolaeNMV/2682fb923f6e91213985b67a02974c0b to your computer and use it in GitHub Desktop.
Encode/Decode Ascii->Binary->Base64 in Scala
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Multistep encoding of ascii to binary->base64 | |
// As the binary will be presented as blocks of 0,1 separated by space. | |
// The base64 result will contain patterns such as MTA, MCA, IDE. | |
val message = "Hello World !" | |
def encode(message: String): String = | |
java.util.Base64.getEncoder().encodeToString( message.map(_.toBinaryString).mkString(" ").map(_.toByte).toArray ) | |
def decode(base64: String): String = | |
new String( java.util.Base64.getDecoder.decode(base64)).split(" ").map(b => Integer.parseInt(b,2).toChar).mkString | |
val base64 = encode(message) | |
println(s"Encoded as base64: $base64") | |
// Encoded as base64: MTAwMTAwMCAxMTAwMTAxIDExMDExMDAgMTEwMTEwMCAxMTAxMTExIDEwMDAwMCAxMDEwMTExIDExMDExMTEgMTExMDAxMCAxMTAxMTAwIDExMDAxMDAgMTAwMDAwIDEwMDAwMQ== | |
println(s"Decoded ${decode(base64)}") | |
// Decoded Hello World ! |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment