Skip to content

Instantly share code, notes, and snippets.

@digital-diplomat
Created March 8, 2023 02:13
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/2beaceff8ad5bdcb38e0c948238eccd7 to your computer and use it in GitHub Desktop.
Save digital-diplomat/2beaceff8ad5bdcb38e0c948238eccd7 to your computer and use it in GitHub Desktop.
Program to translate HEX and ASCII, rewritten in Kotlin
// 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.
*/
fun decodeHex(input: String): String {
return input
.split(Regex("(\\s|,)+")) // Split into individual values
.map { Integer.parseInt(it, 16) } // Parse as hex into numbers
.map { it.toChar() } // Convert numbers to ASCII
.joinToString(""); // Merge results into a string
}
/**
* Converts a regular string into the equivalent hexadecimal values.
*
* @param input Any string of valid ASCII/Unicode characters.
*/
fun encodeHex(input: String): String {
return input
.map{it.code.toString(16)} // Convert to number, then hex
.joinToString(" "); // Merge with space separators
}
/** Main Program */
fun main() {
print("(E)ncode, (D)ecode, or (Q)uit?\n> ");
val opt = readLine()?.first(); // Prompt to select function
when (opt) {
'e','E' -> { // Encode to HEX
print("Enter string to encode.\n> ");
println("= " + encodeHex(readLine().orEmpty()) + "\n");
main();
}
'f','F' -> { // Press F to pay respects.
println("Respects have been paid.\n")
main();
}
'd','D' -> {
println("Enter HEX string to decode."); // Decode from HEX
print("Separate values with commas and/or spaces.\n> ");
try {
println("= " + decodeHex(readLine().orEmpty()) + "\n");
} catch (e: NumberFormatException) {
// If user enters invalid string, give error and retry.
println("Please enter valid hexadecimal, and use " +
"only commas and spaces " +
"to separate each value.\n");
} catch (e: Exception) {
System.err.println("An unknown error has occurred."); // If there's some other error, print
System.exit(1); // message and quit w/ error code 1.
} finally {
main();
}
}
'q','Q' -> { // Quit program
System.exit(0);
}
else -> { // If other selection is made,
println("Please enter a valid command.\n"); // give error message.
main();
}
}
} // :]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment