Created
March 8, 2023 02:13
-
-
Save digital-diplomat/2beaceff8ad5bdcb38e0c948238eccd7 to your computer and use it in GitHub Desktop.
Program to translate HEX and ASCII, rewritten in Kotlin
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
// 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