Last active
February 27, 2020 11:24
-
-
Save CattenLinger/f232fc92a4ed0c3ff57ac603d3ed5e44 to your computer and use it in GitHub Desktop.
周易 BASE 六十四卦
This file contains 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
import java.io.ByteArrayOutputStream | |
object Hexagram64 { | |
private const val zero = '䷀' | |
private const val nil = '⚋' | |
fun parse(string: String): ByteArray = ByteArrayOutputStream(128).use { stream -> | |
var count = 0 | |
var length = 0 | |
var data = 0 | |
for (char in string) { | |
val bits = if (char == nil) -1 else char.minus(zero).takeIf { it in 0..64 } ?: continue | |
data = data shl 6 or bits.coerceAtLeast(0) | |
if(bits > -1) length++ | |
if (++count > 3) { | |
count = 0 | |
while (length-- > 1) { | |
stream.write(data and 0xFF0000 ushr 16) | |
data = data shl 8 and 0xFFFFFF | |
} | |
} | |
} | |
stream.toByteArray() | |
} | |
fun rend(byteArray: ByteArray): String = StringBuilder().apply { | |
val size = byteArray.size | |
var padding = 0 | |
var i = 0 | |
while (i < size) { | |
var group = 0 | |
repeat(3) { | |
group = group shl 8 | |
if (i < size) group = group or (byteArray[i++].toInt() and 0xFF) else padding++ | |
} | |
repeat(4 - padding) { | |
val index = group ushr 18 and 0x3F | |
append(zero + index) | |
group = group shl 6 | |
} | |
} | |
repeat(padding) { append(nil) } | |
}.toString() | |
} | |
fun main() { | |
val content = "Hello world!" | |
val encoded = Hexagram64.rend(content.toByteArray()) | |
val decoded = String(Hexagram64.parse(encoded), Charsets.UTF_8) | |
println(""" | |
Origin : $content | |
Encoded : $encoded | |
Decoded : $decoded | |
""".trimIndent()) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment