Skip to content

Instantly share code, notes, and snippets.

@trumanw
Created April 20, 2015 07:08
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save trumanw/ef3bd4c5adaa7cec4acc to your computer and use it in GitHub Desktop.
Save trumanw/ef3bd4c5adaa7cec4acc to your computer and use it in GitHub Desktop.
String to hex bytes String in Scala.
object HexStringUtil {
// convert normal string to hex bytes string
def string2hex(str: String): String = {
str.toList.map(_.toInt.toHexString).mkString
}
// convert hex bytes string to normal string
def hex2string(hex: String): String = {
hex.sliding(2, 2).toArray.map(Integer.parseInt(_, 16).toChar).mkString
}
def demo {
val appkey = "9GLV//lv/kYFW2o3/bihxwnMcmo="
// string to hex
val appkey_hex = string2hex(appkey)
// 39474c562f2f6c762f6b594657326f332f62696878776e4d636d6f3d
println(appkey_hex)
// hex to string
val appkey_string_again = hex2string(appkey_hex)
// 9GLV//lv/kYFW2o3/bihxwnMcmo=
println(appkey_string_again)
}
}
@shiro-siben
Copy link

没有显示结果是0x1c、0x02等等这种形式的嘛

@fabi-alstom
Copy link

Is this valid? Don't .toHexString strips leading zeroes?

@techmag
Copy link

techmag commented Jan 8, 2024

This seems to pass tests in ScalaCheck much better...

 def stringToHex(input: String): String = {
    input.getBytes(java.nio.charset.StandardCharsets.UTF_8)
      .map("%02x".format(_))
      .mkString
  }

  def hexToString(hex: String): String = {
    val byteArray = hex.sliding(2, 2).toArray.map(hexPair => Integer.parseInt(hexPair, 16).toByte)
    new String(byteArray, java.nio.charset.StandardCharsets.UTF_8)
  }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment