I was considering recently to implement a dynamic part for my ESP8266 web server password. Roman numerals seemed like a nice idea since I only need to know the current time for that part of the password. After some research into this topic, I have not found any example online that worked for me. I tried to find Java example for a converter, and there is a very nice, elegant solution for that. After trying to replicate its logic, I have made a working code that converts Roman numerals to Arabic numbers and back. I hope you find it helpful.
The input string is evaluated to verify if it has numeric value or not:
boolean isValidNumber(String str) {
if (str.length() == 0) return false;
for (byte i = 0; i < str.length(); i++)
{
if (!isDigit(str.charAt(i))) return false;
}
return true;
}
Based on the value of the string, the appropriate function is called:
if (isValidNumber(input)) {
Serial.print(" converted to Roman numerals is: ");
Serial.println(toRoman(input.toInt()));
} else {
Serial.print(" converted to Arabic numbers is: ");
Serial.println(toArabic(input));
}
Both functions are working on the same principle. The input string is compared with all values from multidimensional array.
const String numberMatrix[14][2] = {
{"1000", "M"},
{"900", "CM"},
{"500", "D"},
{"400", "CD"},
{"100", "C"},
{"90", "XC"},
{"50", "L"},
{"40", "XL"},
{"10", "X"},
{"9", "IX"},
{"5", "V"},
{"4", "IV"},
{"1", "I"},
{"0", ""}
};
Every found value is removed from the input string and the result is added to the output.
If not needed, either to Arabic or to Roman functions can be removed with their number matrix and floor functions since both parts are independent.
Java code that helped me write this code is attached to this project.
Comments
Please log in or sign up to comment.