Website Summary Files Commits Branches @commit @diff @stats
path: root / Sem. 07
diff options
context:
space:
mode:
Commit930bb7663e4e70a4c8aa186cb03aa90a006c19e8 (patch)
Author
 Angel Dimitriev <achi_d@abv.bg>
2021-11-17 18:59:03 +0200
Committer
 GitHub <noreply@github.com>
2021-11-17 18:59:03 +0200
Files111a06dfb94bba4f7b24f85a827a0b8d59fbaaa0 /Sem. 07
Introduction_to_programming_FMI-930bb7663e4e70a4c8aa186cb03aa90a006c19e8.tar
Introduction_to_programming_FMI-930bb7663e4e70a4c8aa186cb03aa90a006c19e8.tar.gz
Introduction_to_programming_FMI-930bb7663e4e70a4c8aa186cb03aa90a006c19e8.zip
Parentae971855111460bc4f0ff98fdb8d6283c9c821bd (diff)
Create numerialSystemsExample.cpp
1 files changed, 98 insertions, 0 deletions
-rw-r--r--Sem. 07/numerialSystemsExample.cpp98
diff --git a/Sem. 07/numerialSystemsExample.cpp b/Sem. 07/numerialSystemsExample.cpp
new file mode 100644
index 0000000..620804c
--- /dev/null
+++ b/Sem. 07/numerialSystemsExample.cpp
@@ -0,0 +1,98 @@
+#include <iostream>
+using namespace std;
+
+const unsigned MAX_SIZE = 32;
+
+char getCharByNumber(unsigned number)
+{
+ if (number <= 9)
+ return '0' + number;
+ if (10 <= number && number <= 35)
+ return 'A' + (number - 10);
+ else
+ return 'a' + (number - 36);
+}
+
+unsigned getNumberByChar(char ch)
+{
+ if ('0' <= ch && ch <= '9')
+ return ch - '0';
+ if ('A' <= ch && ch <= 'Z')
+ return 10 + ch - 'A';
+ if ('a' <= ch && ch <= 'z')
+ return 32 + ch - 'a';
+}
+
+void swap(int& a, int& b)
+{
+ int temp = a;
+ a = b;
+ b = temp;
+}
+void convertFromDecimal(unsigned number, char result[], unsigned k)
+{
+ unsigned resultInd = 0;
+ while (number != 0)
+ {
+ int symbolIndex = number % k;
+ result[resultInd++] = getCharByNumber(symbolIndex);
+ number /= k;
+ }
+
+ for (unsigned i = 0; i < resultInd / 2; i++)
+ swap(result[i], result[resultInd - 1 - i]);
+
+}
+
+unsigned convertToDecimal(const char number[], unsigned size, unsigned k)
+{
+ unsigned mult = 1;
+
+ unsigned result = 0;
+ for (int i = size - 1; i >= 0; i--)
+ {
+ result += getNumberByChar(number[i]) * mult;
+ mult *= k;
+ }
+
+ return result;
+}
+
+//fill with spaces from start
+void init(char buff[], unsigned start)
+{
+ for (unsigned i = start; i < MAX_SIZE; i++)
+ buff[i] = ' ';
+}
+
+void print(const char buff[])
+{
+ for (unsigned i = 0; i < MAX_SIZE; i++)
+ cout << buff[i];
+ cout << endl;
+}
+
+int main()
+{
+ {
+ unsigned n = 12345;
+ char buff[MAX_SIZE];
+ init(buff, 0);
+
+ convertFromDecimal(123456, buff, 16);
+
+ cout << n << " to hex: ";
+ print(buff);
+ }
+
+ {
+ unsigned n = 12345;
+ char buff[MAX_SIZE] = { 'A', '1', '2', 'B' };
+ init(buff, 5);
+
+ unsigned result = convertToDecimal(buff, 4, 16);
+
+ cout << buff << " to decimal: " << result << endl;
+ }
+}
+