Skip to content

Instantly share code, notes, and snippets.

@nachinius
Last active April 15, 2019 15:54
Show Gist options
  • Save nachinius/8de7e09518d71bccdbed7bbcda5d6f8e to your computer and use it in GitHub Desktop.
Save nachinius/8de7e09518d71bccdbed7bbcda5d6f8e to your computer and use it in GitHub Desktop.
scala hex to base32. Finding the prefix for addresses in NEM crypto
#!/usr/bin/env amm
import $ivy.`org.apache.hadoop:hadoop-common:3.2.0`, org.apache.commons.codec.binary.Base32
// HexBytesUtil from https://gist.githubusercontent.com/tmyymmt/3721117/raw/70af27f30df0ec0084e37e7fe3ff0a547bf8020b/HexBytesUtil.scala
object HexBytesUtil {
def hex2bytes(hex: String): Array[Byte] = {
if(hex.contains(" ")){
hex.split(" ").map(Integer.parseInt(_, 16).toByte)
} else if(hex.contains("-")){
hex.split("-").map(Integer.parseInt(_, 16).toByte)
} else {
hex.sliding(2,2).toArray.map(Integer.parseInt(_, 16).toByte)
}
}
def bytes2hex(bytes: Array[Byte], sep: Option[String] = None): String = {
sep match {
case None => bytes.map("%02x".format(_)).mkString
case _ => bytes.map("%02x".format(_)).mkString(sep.get)
}
// bytes.foreach(println)
}
def example {
val data = "48 65 6C 6C 6F 20 57 6F 72 6C 64 21 21"
val bytes = hex2bytes(data)
println(bytes2hex(bytes, Option(" ")))
val data2 = "48-65-6C-6C-6F-20-57-6F-72-6C-64-21-21"
val bytes2 = hex2bytes(data2)
println(bytes2hex(bytes2, Option("-")))
val data3 = "48656C6C6F20576F726C642121"
val bytes3 = hex2bytes(data3)
println(bytes2hex(bytes3))
}
}
val base32 = new Base32
def transform(hexNoPrefix: String): String = {
val arrayOfBytes = HexBytesUtil.hex2bytes(hexNoPrefix)
base32.encodeAsString(arrayOfBytes)
}
def printTransformation(hexNoPrefix: String): Unit = {
print("hex is "+hexNoPrefix)
println(" whose convertion is " + transform(hexNoPrefix))
}
printTransformation("68") // main net NEM
printTransformation("98") // test net NEM
~
~
~
~
"encoding.base32.hex.sc" 58L, 1652C written
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment