Created
April 20, 2015 07:08
-
-
Save trumanw/ef3bd4c5adaa7cec4acc to your computer and use it in GitHub Desktop.
String to hex bytes String in Scala.
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
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) | |
} | |
} |
Is this valid? Don't .toHexString strips leading zeroes?
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
没有显示结果是0x1c、0x02等等这种形式的嘛