Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

Лабараторная

.doc
Скачиваний:
4
Добавлен:
31.01.2023
Размер:
816.13 Кб
Скачать

МИНОБРНАУКИ РОССИИ

Санкт-Петербургский государственный

электротехнический университет

«ЛЭТИ» им. В.И. Ульянова (Ленина)

Кафедра вычислительной техники

отчет

по лабораторной работе №1

по дисциплине «Организация ЭВМ и систем»

Тема: Исследование внутреннего представления

различных форматов данных

Студент гр. 8091

Гришин И.Д.

Преподаватель

Павлов С.М.

Санкт-Петербург

2021

Задание

Дать возможность пользователю выбрать тип данных из числа предложенных Вами, включая данные с плавающей запятой. Далее предложить пользователю выбрать систему счисления, в которой он будет это данное вводить. При выборе символьного типа предложить вводить символ или код символа в выбранной системе счисления. При вводе цифр (символов) данного НЕ ДОПУСКАТЬ видимого отображения на экране символов, не использующихся в выбранном типе или системе счисления. После необходимых вычислений вывести полученного значение в 10-ой системе счисления и внутреннее представление этого данного в виде соответствующего количества бит.

Дополнительное задание: установить в заданное пользователем состояние определённое количество рядом стоящих бит, номер старшего бита, как и всё остальное, вводится с клавиатуры.

Дополнительное задание: выполнить раскраску изменённых бит в данном в выбранный пользователем цвет из числа предложенных Вами.

Дополнительное задание: дополнить программу ассемблерными вставками, где будут использоваться поразрядные логические операции при преобразовании данных и регистры процессора.

Дополнительное задание: отобразить содержимое ОЗУ.

.

Блок-схема

Рисунок 1. Блок-схема программы

Текст программы

#include <iostream> #include <cmath> #include <sstream> #include <iomanip> using namespace std; string colors[] = { "\033[30m", // black "\033[31m", // red "\033[32m", // green "\033[33m", // yellow "\033[34m", // blue "\033[35m", // magenta "\033[36m", // cyan "\033[37m", // white "\033[0m", // reset }; union number { double d; uint64_t i; }; string displayBitsDouble (double d) { string result; union number n; n.d = d; uint64_t base = 1; result = to_string((n.i & (base << 63))); for (int i = 62; i >= 0; --i) { result += to_string((n.i & (base << i)) >> i); } // printf("Address at DisplayBitsDouble of d is %p\n", &d); // printf("Address at DisplayBitsDouble of result is %p\n", &result); // printf("Address at DisplayBitsDouble of number is %p\n", &n); // printf("Address at DisplayBitsDouble of number.d is %p\n", &n.d); // printf("Address at DisplayBitsDouble of base is %p\n", &base); return result; } int displayBitsInt (int value) { int val = 0; string result; for (int i = sizeof(int) * 8 - 1; i >= 0; --i) { // val = (value >> i) & 1; asm volatile ( "lsr %w[val], %w[value], %w[i] \n" "and %w[val], %w[val], 1 \n" : [val] "=r" (val) : [i] "r" (i), [value] "r" (value) : ); result += to_string(val); } // printf("Address at DisplayBitsInt of value is %p\n", &value); // printf("Address at DisplayBitsInt of val is %p\n", &val); // printf("Address at DisplayBitsInt of result is %p\n", &result); return stoi(result); } string double2String (double value) { ostringstream os; os << setprecision(10) << value; string str = os.str(); // printf("Address at Double2String of value is %p\n", &value); // printf("Address at Double2String of value is %p\n", &os); // printf("Address at Double2String of value is %p\n", &str); return str; } string double2decimal (string value, int base) { string number = value; double ans = 0; int pointPos = 0; int size = number.length(); for (int i = 0; i < number.length(); i++) { if (number[i] == '.') { pointPos = i; break; } } if (pointPos == 0) { for (int i = 0; i < size; i++) ans += (number[i] - '0') * pow(base, size - i - 1); } else { for (int i = 0; i < pointPos; i++) ans += (number[i] - '0') * pow(base, pointPos - i - 1); for (int i = pointPos + 1; i < size; i++) ans += (number[i] - '0') * pow(base, -i + pointPos); } // printf("Address at Double2decimal of value is %p\n", &value); // printf("Address at Double2decimal of base is %p\n", &base); // printf("Address at Double2decimal of number is %p\n", &number); // printf("Address at Double2decimal of ans is %p\n", &ans); // printf("Address at Double2decimal of pointPos is %p\n", &pointPos); // printf("Address at Double2decimal of size is %p\n", &size); return to_string(ans); } int int2decimal (string value, int base) { int result = 0; int size = value.length(); for (int i = 0; i < size; i++) { if(value[i] >= 'A') { result += (value[i] - 'A' + 10) * pow(base, size - i - 1); } else { result += (value[i] - '0') * pow(base, size - i - 1); } } // printf("Address at Int2decimal of value is %p\n", &value); // printf("Address at Int2decimal of value is %p\n", &base); // printf("Address at Int2decimal of value is %p\n", &result); // printf("Address at Int2decimal of value is %p\n", &size); return result; } string doubleBin2Dec (string value, int base) { double result = 0, m = 0, e = 0; for (int i = 1; i < 12; i++) e += (value[i] - '0') * pow(2, 11 - i); for (int i = 12; i < 64; i++) m += (value[i] - '0') * pow(2, 11 - i); result = pow(-1, (value[0] - '0')) * pow(2, e - 1023) * (m + 1); // printf("Address at DoubleBin2Dec of value is %p\n", &value); // printf("Address at DoubleBin2Dec of base is %p\n", &base); // printf("Address at DoubleBin2Dec of result is %p\n", &result); // printf("Address at DoubleBin2Dec of m is %p\n", &m); // printf("Address at DoubleBin2Dec of e is %p\n", &e); return double2decimal(double2String(result), base); } void logicOperation (string bits, int highBit, int num, int state, int base, int type) { int color, length = highBit + num; cout << "Выберите цвет для окрашивания: 1) Чёрный, 2) Красный, 3) Зелёный, 4) Жёлтый, 5) Синий, 6) Пурпурный, 7) Бирюзовый, 8) Белый: "; cin >> color; cout << endl << "Исходное представление: " << bits; switch (state) { case 0: { for (int i = highBit; i < length; i++) bits[i] = '0'; } case 1: { for (int i = highBit; i < length; i++) bits[i] = '1'; } } cout << endl << "Результат состояния: "; for (int i = 0; i <= bits.length() - 1; i++) { if (i >= highBit && i < length) cout << colors[color - 1] << bits[i] << colors[8]; else cout << bits[i]; } if (type == 0) cout << endl << "В десятичной форме: " << doubleBin2Dec(bits, base) << endl; else cout << endl << "В десятичной форме: " << int2decimal(bits, base) << endl; // printf("Address at LogicOperation of bits is %p\n", &bits); // printf("Address at LogicOperation of highBit is %p\n", &highBit); // printf("Address at LogicOperation of num is %p\n", &num); // printf("Address at LogicOperation of state is %p\n", &state); // printf("Address at LogicOperation of base is %p\n", &base); // printf("Address at LogicOperation of type is %p\n", &type); // printf("Address at LogicOperation of color is %p\n", &color); // printf("Address at LogicOperation of length is %p\n", &length); // printf("Address at LogicOperation of colors is %p\n", &colors); } void designInt(int base) { string value; int input; bool inputResult; char baseChar = (base == 4) ? '4' : '8'; int valuePosBit, valueNum, valueState; cout << "Введите значение в " << base << "-й форме: "; do { cin >> input; value = double2String(input); for (char i : value) { inputResult = i < baseChar; if (!inputResult) { cerr << "Число не соответствует условию. Попробуйте снова: "; break; } } } while (!inputResult); cout << "В десятичной форме: " << int2decimal(to_string(input), base) << endl; cout << "Битовое представление числа: " << displayBitsInt(int2decimal(to_string(input), base)) << endl; cout << "Введите позицию старшего бита: "; cin >> valuePosBit; cout << "Введите кол-во бит для изменения: "; cin >> valueNum; cout << "В какое состояние привести эти биты – 0 или 1: "; cin >> valueState; logicOperation(to_string(displayBitsInt(int2decimal(to_string(input), base))), valuePosBit, valueNum, valueState, 2, 1); // printf("Address at DesignInt of value is %p\n", &value); // printf("Address at DesignInt of input is %p\n", &input); // printf("Address at DesignInt of inputResult is %p\n", &inputResult); // printf("Address at DesignInt of base is %p\n", &base); // printf("Address at DesignInt of baseChar is %p\n", &baseChar); // printf("Address at DesignInt of valueState is %p\n", &valueState); // printf("Address at DesignInt of valueNum is %p\n", &valueNum); // printf("Address at DesignInt of valuePosBit is %p\n", &valuePosBit); } void designDouble (int base) { string value; double input; bool inputResult; char baseChar = (base == 4) ? '4' : '8'; int valuePosBit, valueNum, valueState; cout << "Введите значение в " << base << "-й форме: "; do { cin >> input; value = double2String(input); for (char i : value) { inputResult = i < baseChar; if (!inputResult) { cerr << "Число не соответствует условию. Попробуйте снова: "; break; } } } while (!inputResult); cout << "В десятичной форме: " << double2decimal(double2String(input), base) << endl; cout << "Битовое представление числа: " << displayBitsDouble(input) << endl; cout << "Введите позицию старшего бита: "; cin >> valuePosBit; cout << "Введите кол-во бит для изменения: "; cin >> valueNum; cout << "В какое состояние привести эти биты – 0 или 1: "; cin >> valueState; logicOperation(displayBitsDouble(input), valuePosBit, valueNum, valueState, base, 0); // printf("Address at DesignDouble of value is %p\n", &value); // printf("Address at DesignDouble of input is %p\n", &input); // printf("Address at DesignDouble of inputResult is %p\n", &inputResult); // printf("Address at DesignDouble of base is %p\n", &base); // printf("Address at DesignDouble of baseChar is %p\n", &baseChar); // printf("Address at DesignDouble of valueState is %p\n", &valueState); // printf("Address at DesignDouble of valueNum is %p\n", &valueNum); // printf("Address at DesignDouble of valuePosBit is %p\n", &valuePosBit); } int main () { int choice, notation; int notationSystem[] = { 4, 8 }; do { cout << "Выберите тип данных: 1) int, 2) double — "; cin >> choice; cout << "Выберите систему счисления для ввода числа: 1) 4, 2) 8 — "; cin >> notation; switch (choice) { case 1: designInt(notationSystem[notation - 1]); break; case 2: designDouble(notationSystem[notation - 1]); break; } } while (choice != 1 && choice != 2); // printf("Address of choice is %p\n", &choice); // printf("Address of notation is %p\n", &notation); }

Пример запуска программы

Рисунок 2. Пример запуска программы

Рисунок 3. Пример запуска программы

Вывод адресов переменных программы

Address at Double2String of value is 0x16d197640

Address at Double2String of value is 0x16d197538

Address at Double2String of value is 0x16d197760

Address at Int2decimal of value is 0x16d197728

Address at Int2decimal of value is 0x16d19765c

Address at Int2decimal of value is 0x16d197658

Address at Int2decimal of value is 0x16d197654

Address at Int2decimal of value is 0x16d19765c

Address at Int2decimal of value is 0x16d197658

Address at Int2decimal of value is 0x16d197654

Address at DisplayBitsInt of value is 0x16d19765c

Address at DisplayBitsInt of val is 0x16d197658

Address at DisplayBitsInt of result is 0x16d197640

Address at Int2decimal of value is 0x16d1976e0

Address at Int2decimal of value is 0x16d19765c

Address at Int2decimal of value is 0x16d197658

Address at Int2decimal of value is 0x16d197654

Address at DisplayBitsInt of value is 0x16d19765c

Address at DisplayBitsInt of val is 0x16d197658

Address at DisplayBitsInt of result is 0x16d197640

Address at Int2decimal of value is 0x16d1975d0

Address at Int2decimal of value is 0x16d19753c

Address at Int2decimal of value is 0x16d197538

Address at Int2decimal of value is 0x16d197534

Address at LogicOperation of bits is 0x16d1976f8

Address at LogicOperation of highBit is 0x16d19764c

Address at LogicOperation of num is 0x16d197648

Address at LogicOperation of state is 0x16d197644

Address at LogicOperation of base is 0x16d197640

Address at LogicOperation of type is 0x16d19763c

Address at LogicOperation of color is 0x16d197638

Address at LogicOperation of length is 0x16d197634

Address at LogicOperation of colors is 0x102c741f8

Address at DesignInt of value is 0x16d1977a0

Address at DesignInt of input is 0x16d19779c

Address at DesignInt of inputResult is 0x16d19779b

Address at DesignInt of base is 0x16d1977bc

Address at DesignInt of baseChar is 0x16d19779a

Address at DesignInt of valueState is 0x16d19778c

Address at DesignInt of valueNum is 0x16d197790

Address at DesignInt of valuePosBit is 0x16d197794

Address of choice is 0x16d197818

Address of notation is 0x16d197814

Структурная схема аппаратных средств

Рисунок 4. Пример запуска программы

10

Соседние файлы в предмете Организация ЭВМ и вычислительных систем