Convert.cpp 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. #include "Convert.h"
  2. #include "Settings.h"
  3. #include <QString>
  4. int stringToValue(const QString& str)
  5. {
  6. QString s = str.trimmed();
  7. int base = 10;
  8. // find base (prefix or postfix)
  9. if (s.startsWith("&") && s.size() >= 2) {
  10. switch (s[1].toUpper().toLatin1()) {
  11. case 'H':
  12. base = 16;
  13. break;
  14. case 'B':
  15. base = 2;
  16. break;
  17. case 'O':
  18. base = 8;
  19. break;
  20. }
  21. s = s.remove(0, 2);
  22. } else if (s.startsWith("#") || s.startsWith("$")) {
  23. base = 16;
  24. s = s.remove(0, 1);
  25. } else if (s.startsWith("0x")) {
  26. base = 16;
  27. s = s.remove(0, 2);
  28. } else if (s.startsWith("%")) {
  29. base = 2;
  30. s = s.remove(0, 1);
  31. } else if (!s.isEmpty()) {
  32. switch (s.right(1)[0].toUpper().toLatin1()) {
  33. case 'H':
  34. case '#':
  35. base = 16;
  36. break;
  37. case 'B':
  38. base = 2;
  39. break;
  40. case 'O':
  41. base = 8;
  42. break;
  43. }
  44. if (base != 10) s.chop(1);
  45. }
  46. // convert value
  47. bool ok;
  48. int value = s.toInt(&ok, base);
  49. if (!ok) return -1;
  50. return value;
  51. }
  52. QString hexValue(int value, int width)
  53. {
  54. Settings& s = Settings::get();
  55. return QString("%1%2%3").arg(s.value("Preferences/HexPrefix", "$").toString())
  56. .arg(value, width, 16, QChar('0'))
  57. .arg(s.value("Preferences/HexPostfix", "").toString());
  58. }
  59. QString& escapeXML(QString& str)
  60. {
  61. return str.replace('&', "&amp;").replace('<', "&lt;").replace('>', "&gt;");
  62. }
  63. QString& unescapeXML(QString& str)
  64. {
  65. return str.replace("&amp;", "&").replace("&lt;", "<").replace("&gt;", ">");
  66. }