Last active
October 24, 2017 13:04
-
-
Save ykon/7f547105c06c9e138ae11d5288e4d565 to your computer and use it in GitHub Desktop.
Hex string in Scala
This file contains hidden or 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
/* | |
* Copyright (c) 2017 Yuki Ono | |
* Licensed under the MIT License. | |
*/ | |
package func_hex | |
import Integer.toHexString | |
import Integer.parseInt | |
object Hex extends App { | |
def proceduralEncode(bytes: Array[Byte]): String = { | |
val sb = new StringBuffer(bytes.length * 2) | |
for (b <- bytes) { | |
sb.append(toHexString((b >>> 4) & 0x0F)) | |
sb.append(toHexString(b & 0x0F)) | |
} | |
sb.toString() | |
} | |
def fpEncode(bytes: Array[Byte]): String = { | |
def toRight(b: Byte) = toHexString((b >>> 4) & 0x0F) | |
def toLeft(b: Byte) = toHexString(b & 0x0F); | |
//bytes.map(b => toRight(b) + toLeft(b)).mkString | |
bytes.flatMap(b => Array(toRight(b), toLeft(b))).mkString | |
} | |
def proceduralDecode(hex: String): Array[Byte] = { | |
require(hex.length % 2 == 0) | |
val bytes = new Array[Byte](hex.length / 2) | |
var i = 0 | |
while (i < bytes.length) { | |
bytes(i) = parseInt(hex.substring(i * 2, i * 2 + 2), 16).toByte | |
i += 1 | |
} | |
bytes | |
} | |
def fpDecode(hex: String): Array[Byte] = { | |
require(hex.length % 2 == 0) | |
def hexToByte(s: String) = parseInt(s, 16).toByte | |
hex.grouped(2).map(hexToByte).toArray | |
} | |
val testBytes = Array(1, 2, 3, 4, 5, 11, 12, 13, 14, 15, 251, 252, 253, 254, 255).map(_.toByte) | |
println(proceduralEncode(testBytes)) | |
println(fpEncode(testBytes)) | |
val testHex = "01020304050b0c0d0e0ffbfcfdfeff" | |
println(proceduralDecode(testHex).mkString(",")) | |
println(fpDecode(testHex).mkString(",")) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment