Skip to content

Instantly share code, notes, and snippets.

@digital-diplomat
Created June 10, 2022 18:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save digital-diplomat/73881dce848cdb3b56c8311d6f0ef345 to your computer and use it in GitHub Desktop.
Save digital-diplomat/73881dce848cdb3b56c8311d6f0ef345 to your computer and use it in GitHub Desktop.
Scala program to translate between HEX and ASCII
// Program to encode/decode hexadecimal and ASCII/Unicode
/**
* Decodes a string of hexadecimal numbers into a string of characters.
*
* @param input A string with only valid HEX numbers separated by spaces and/or commas.
*/
def decodeHex(input: String): String = {
input
.split("(\\s|,)+") // Split into individual values
.map(Integer.parseInt(_, 16)) // Parse as hex into numbers
.map(_.toChar) // Convert numbers to ASCII
.mkString; // Merge results into a string
}
/**
* Converts a regular string into the equivalent hexadecimal values.
*
* @param input Any string of valid ASCII/Unicode characters.
*/
def encodeHex(input: String): String = {
input
.map(_.toInt.toHexString) // Convert to number, then hex
.mkString(" "); // Merge with space separators
}
/** Main Program */
@main def HexLib() : Unit = {
print("(E)ncode, (D)ecode, or (Q)uit?\n> ");
val opt = Console.in.readLine().charAt(0); // Prompt to select function
opt match {
case 'e' | 'E' => { // Encode to HEX
print("Enter string to encode.\n> ");
println("= " + encodeHex(Console.in.readLine()) + "\n");
HexLib();
}
case 'f' | 'F' => { // Press F to pay respects.
println("Respects have been paid.\n")
HexLib();
}
case 'd' | 'D' => {
println("Enter HEX string to decode."); // Decode from HEX
print("Separate values with commas and/or spaces.\n> ");
try {
println("= " + decodeHex(Console.in.readLine()) + "\n");
} catch {
case e : NumberFormatException => { // If user enters invalid
println("Please enter valid hexadecimal, and use " + // string, give error and retry.
"only commas and spaces " +
"to separate each value.\n");
}
case x : Exception => {
System.err.println(x.getMessage); // If there's some other error, print
System.exit(1); // message and quit w/ error code 1.
}
} finally { HexLib(); }
}
case 'q' | 'Q' => { // Quit program
System.exit(0);
}
case _ => { // If other selection is made,
println("Please enter a valid command.\n"); // give error message.
HexLib();
}
}
} // :]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment