Skip to content

Instantly share code, notes, and snippets.

@NicolaeNMV
Last active September 15, 2018 16:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save NicolaeNMV/2682fb923f6e91213985b67a02974c0b to your computer and use it in GitHub Desktop.
Save NicolaeNMV/2682fb923f6e91213985b67a02974c0b to your computer and use it in GitHub Desktop.
Encode/Decode Ascii->Binary->Base64 in Scala
// 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