diff --git a/.clang-format b/.clang-format new file mode 100644 index 0000000..84ea374 --- /dev/null +++ b/.clang-format @@ -0,0 +1,244 @@ +--- +Language: Cpp +# BasedOnStyle: WebKit +AccessModifierOffset: -4 +AlignAfterOpenBracket: DontAlign +AlignArrayOfStructures: None +AlignConsecutiveAssignments: + Enabled: false + AcrossEmptyLines: false + AcrossComments: false + AlignCompound: false + AlignFunctionPointers: false + PadOperators: true +AlignConsecutiveBitFields: + Enabled: false + AcrossEmptyLines: false + AcrossComments: false + AlignCompound: false + AlignFunctionPointers: false + PadOperators: false +AlignConsecutiveDeclarations: + Enabled: false + AcrossEmptyLines: false + AcrossComments: false + AlignCompound: false + AlignFunctionPointers: false + PadOperators: false +AlignConsecutiveMacros: + Enabled: false + AcrossEmptyLines: false + AcrossComments: false + AlignCompound: false + AlignFunctionPointers: false + PadOperators: false +AlignConsecutiveShortCaseStatements: + Enabled: false + AcrossEmptyLines: false + AcrossComments: false + AlignCaseColons: false +AlignEscapedNewlines: Right +AlignOperands: DontAlign +AlignTrailingComments: + Kind: Never + OverEmptyLines: 0 +AllowAllArgumentsOnNextLine: true +AllowAllParametersOfDeclarationOnNextLine: true +AllowBreakBeforeNoexceptSpecifier: Never +AllowShortBlocksOnASingleLine: Empty +AllowShortCaseLabelsOnASingleLine: false +AllowShortCompoundRequirementOnASingleLine: true +AllowShortEnumsOnASingleLine: true +AllowShortFunctionsOnASingleLine: All +AllowShortIfStatementsOnASingleLine: Never +AllowShortLambdasOnASingleLine: All +AllowShortLoopsOnASingleLine: false +AlwaysBreakAfterDefinitionReturnType: None +AlwaysBreakAfterReturnType: None +AlwaysBreakBeforeMultilineStrings: false +AlwaysBreakTemplateDeclarations: MultiLine +AttributeMacros: + - __capability +BinPackArguments: true +BinPackParameters: true +BitFieldColonSpacing: Both +BraceWrapping: + AfterCaseLabel: false + AfterClass: false + AfterControlStatement: Never + AfterEnum: false + AfterExternBlock: false + AfterFunction: true + AfterNamespace: false + AfterObjCDeclaration: false + AfterStruct: false + AfterUnion: false + BeforeCatch: false + BeforeElse: false + BeforeLambdaBody: false + BeforeWhile: false + IndentBraces: false + SplitEmptyFunction: true + SplitEmptyRecord: true + SplitEmptyNamespace: true +BreakAdjacentStringLiterals: true +BreakAfterAttributes: Leave +BreakAfterJavaFieldAnnotations: false +BreakArrays: true +BreakBeforeBinaryOperators: All +BreakBeforeConceptDeclarations: Always +BreakBeforeBraces: WebKit +BreakBeforeInlineASMColon: OnlyMultiline +BreakBeforeTernaryOperators: true +BreakConstructorInitializers: BeforeComma +BreakInheritanceList: BeforeColon +BreakStringLiterals: true +ColumnLimit: 0 +CommentPragmas: '^ IWYU pragma:' +CompactNamespaces: false +ConstructorInitializerIndentWidth: 4 +ContinuationIndentWidth: 4 +Cpp11BracedListStyle: false +DerivePointerAlignment: false +DisableFormat: false +EmptyLineAfterAccessModifier: Never +EmptyLineBeforeAccessModifier: LogicalBlock +ExperimentalAutoDetectBinPacking: false +FixNamespaceComments: false +ForEachMacros: + - foreach + - Q_FOREACH + - BOOST_FOREACH +IfMacros: + - KJ_IF_MAYBE +IncludeBlocks: Preserve +IncludeCategories: + - Regex: '^"(llvm|llvm-c|clang|clang-c)/' + Priority: 2 + SortPriority: 0 + CaseSensitive: false + - Regex: '^(<|"(gtest|gmock|isl|json)/)' + Priority: 3 + SortPriority: 0 + CaseSensitive: false + - Regex: '.*' + Priority: 1 + SortPriority: 0 + CaseSensitive: false +IncludeIsMainRegex: '(Test)?$' +IncludeIsMainSourceRegex: '' +IndentAccessModifiers: false +IndentCaseBlocks: false +IndentCaseLabels: false +IndentExternBlock: AfterExternBlock +IndentGotoLabels: true +IndentPPDirectives: None +IndentRequiresClause: true +IndentWidth: 4 +IndentWrappedFunctionNames: false +InsertBraces: false +InsertNewlineAtEOF: false +InsertTrailingCommas: None +IntegerLiteralSeparator: + Binary: 0 + BinaryMinDigits: 0 + Decimal: 0 + DecimalMinDigits: 0 + Hex: 0 + HexMinDigits: 0 +JavaScriptQuotes: Leave +JavaScriptWrapImports: true +KeepEmptyLinesAtTheStartOfBlocks: true +KeepEmptyLinesAtEOF: false +LambdaBodyIndentation: Signature +LineEnding: DeriveLF +MacroBlockBegin: '' +MacroBlockEnd: '' +MaxEmptyLinesToKeep: 1 +NamespaceIndentation: Inner +ObjCBinPackProtocolList: Auto +ObjCBlockIndentWidth: 4 +ObjCBreakBeforeNestedBlockParam: true +ObjCSpaceAfterProperty: true +ObjCSpaceBeforeProtocolList: true +PackConstructorInitializers: BinPack +PenaltyBreakAssignment: 2 +PenaltyBreakBeforeFirstCallParameter: 19 +PenaltyBreakComment: 300 +PenaltyBreakFirstLessLess: 120 +PenaltyBreakOpenParenthesis: 0 +PenaltyBreakScopeResolution: 500 +PenaltyBreakString: 1000 +PenaltyBreakTemplateDeclaration: 10 +PenaltyExcessCharacter: 1000000 +PenaltyIndentedWhitespace: 0 +PenaltyReturnTypeOnItsOwnLine: 60 +PointerAlignment: Left +PPIndentWidth: -1 +QualifierAlignment: Leave +ReferenceAlignment: Pointer +ReflowComments: true +RemoveBracesLLVM: false +RemoveParentheses: Leave +RemoveSemicolon: false +RequiresClausePosition: OwnLine +RequiresExpressionIndentation: OuterScope +SeparateDefinitionBlocks: Leave +ShortNamespaceLines: 1 +SkipMacroDefinitionBody: false +SortIncludes: CaseSensitive +SortJavaStaticImport: Before +SortUsingDeclarations: LexicographicNumeric +SpaceAfterCStyleCast: false +SpaceAfterLogicalNot: false +SpaceAfterTemplateKeyword: true +SpaceAroundPointerQualifiers: Default +SpaceBeforeAssignmentOperators: true +SpaceBeforeCaseColon: false +SpaceBeforeCpp11BracedList: true +SpaceBeforeCtorInitializerColon: true +SpaceBeforeInheritanceColon: true +SpaceBeforeJsonColon: false +SpaceBeforeParens: ControlStatements +SpaceBeforeParensOptions: + AfterControlStatements: true + AfterForeachMacros: true + AfterFunctionDefinitionName: false + AfterFunctionDeclarationName: false + AfterIfMacros: true + AfterOverloadedOperator: false + AfterPlacementOperator: true + AfterRequiresInClause: false + AfterRequiresInExpression: false + BeforeNonEmptyParentheses: false +SpaceBeforeRangeBasedForLoopColon: true +SpaceBeforeSquareBrackets: false +SpaceInEmptyBlock: true +SpacesBeforeTrailingComments: 1 +SpacesInAngles: Never +SpacesInContainerLiterals: true +SpacesInLineCommentPrefix: + Minimum: 1 + Maximum: -1 +SpacesInParens: Never +SpacesInParensOptions: + InCStyleCasts: false + InConditionalStatements: false + InEmptyParentheses: false + Other: false +SpacesInSquareBrackets: false +Standard: Latest +StatementAttributeLikeMacros: + - Q_EMIT +StatementMacros: + - Q_UNUSED + - QT_REQUIRE_VERSION +TabWidth: 8 +UseTab: Never +VerilogBreakBetweenInstancePorts: true +WhitespaceSensitiveMacros: + - BOOST_PP_STRINGIZE + - CF_SWIFT_NAME + - NS_SWIFT_NAME + - PP_STRINGIZE + - STRINGIZE \ No newline at end of file diff --git a/CMakeLists.txt b/CMakeLists.txt new file mode 100644 index 0000000..9ea9b95 --- /dev/null +++ b/CMakeLists.txt @@ -0,0 +1,9 @@ +cmake_minimum_required(VERSION 3.25) + +project(C_Homework C) + +add_subdirectory(src/InternalDataRepresentation) + +enable_testing() + +add_compile_options(-Wall -Wextra -Wpedantic) \ No newline at end of file diff --git a/CMakelists.txt b/CMakelists.txt new file mode 100644 index 0000000..da6e315 --- /dev/null +++ b/CMakelists.txt @@ -0,0 +1,7 @@ +cmake_minimum_required(VERSION 3.25) + +project(C_Homework C) + +add_subdirectory(src/InternalDataRepresentation) + +add_compile_options(-Wall -Wextra -Wpedantic) \ No newline at end of file diff --git a/src/InternalDataRepresentation/CMakeLists.txt b/src/InternalDataRepresentation/CMakeLists.txt new file mode 100644 index 0000000..28c81e0 --- /dev/null +++ b/src/InternalDataRepresentation/CMakeLists.txt @@ -0,0 +1,2 @@ +add_executable(binaryRepresentation binaryRepresentation.c testBinaryRepresentation.c) +add_executable(Double DoubleUnderMicroscope.c testDoubleUnderMicroscope.c) \ No newline at end of file diff --git a/src/InternalDataRepresentation/DoubleUnderMicroscope.c b/src/InternalDataRepresentation/DoubleUnderMicroscope.c new file mode 100644 index 0000000..e05ec58 --- /dev/null +++ b/src/InternalDataRepresentation/DoubleUnderMicroscope.c @@ -0,0 +1,55 @@ +#include "lib2.h" +#include +#include +#include + +const char* parseDouble(Number num) +{ + static char result[100]; + uint64_t bits = num.bits; + int sign = (bits >> 63) & 1; + int exponent = (bits >> 52) & 0x7FF; + uint64_t mantissa_bits = bits & 0xFFFFFFFFFFFFF; + double mantissa = 1.0; + double factor = 0.5; + + for (int i = 51; i >= 0; i--) { + if ((mantissa_bits >> i) & 1) { + mantissa += factor; + } + factor *= 0.5; + } + int exp = exponent - 1023; + if (exponent == 0) { + mantissa -= 1.0; + exp = -1022; + } + if (exponent == 0x7FF) { + if (mantissa_bits == 0) { + snprintf(result, sizeof(result), "%cinf", sign ? '-' : '+'); + } else { + snprintf(result, sizeof(result), "nan"); + } + return result; + } + snprintf(result, sizeof(result), "%c%.18g*2^%d", + sign ? '-' : '+', mantissa, exp); + return result; +} + +int main(int argc, char* argv[]) +{ + if (argc == 2 && strcmp(argv[1], "--test") == 0) { + runTests(); + return 0; + } + Number num; + printf("Enter a number: "); + if (scanf("%lf", &num.value) != 1) { + printf("Invalid input\n"); + return 1; + } + const char* result = parseDouble(num); + printf("Result: %s\n", result); + return 0; +} \ No newline at end of file diff --git a/src/InternalDataRepresentation/binaryRepresentation.c b/src/InternalDataRepresentation/binaryRepresentation.c new file mode 100644 index 0000000..7b08bc0 --- /dev/null +++ b/src/InternalDataRepresentation/binaryRepresentation.c @@ -0,0 +1,139 @@ +#include "lib1.h" +#include +#include +#include +#include + +/* +Я выбрала 8ми битное представление чисел, сответственно, +диапазон выбора числа огранчен. от [-128 , 127] - безопасный диапазон. +*/ + +int* simpleConvertionToBin(int n) +{ + int* binary = calloc(8, sizeof(int)); + int i = 7; + while (n > 0 && i >= 0) { + binary[i] = n % 2; + n = n / 2; + i--; + } + return binary; +} + +void addOne(int* binary) +{ + int carry = 1; + int sum = 0; + for (int i = 7; i >= 0; i--) { + int sum = binary[i] + carry; + binary[i] = sum % 2; + if (sum >= 2) { + carry = 1; + } else { + break; + } + } + return; +} + +void invertBits(int* binary) +{ + for (int i = 0; i < 8; i++) { + if (binary[i] == 1) { + binary[i] = 0; + } else { + binary[i] = 1; + } + } + return; +} + +int* convertToBinary(int n) +{ + bool isNegative = false; + if (n < 0) { + isNegative = true; + n = -n; + } + int* binary = simpleConvertionToBin(n); + if (isNegative) { + invertBits(binary); + addOne(binary); + } + return binary; +} + +int* sumBinNumbers(int* fnum, int* snum) +{ + int* sum = calloc(8, sizeof(int)); + int carry = 0; + int bit_sum = 0; + for (int i = 7; i >= 0; i--) { + int bit_sum = fnum[i] + snum[i] + carry; + sum[i] = bit_sum % 2; + carry = bit_sum / 2; + } + return sum; +} + +int convertToDecimal(int* binary) +{ + bool isNegative = false; + if (binary[1] == 1) { + invertBits(binary); + addOne(binary); + isNegative = true; + } + int decimal = 0; + int power = 128; + for (int i = 0; i < 8; i++) { + if (binary[i] == 1) { + decimal += power; + } + power /= 2; + } + if (isNegative) { + return -decimal; + } + return decimal; +} + +int main(int argc, char* argv[]) +{ + if (argc == 2 && strcmp(argv[1], "--test") == 0) { + runTests(); + return 0; + } + int firstNum = 0; + int secNum = 0; + printf("-----------------\n"); + printf("Введите два числа\n"); + scanf("%d %d", &firstNum, &secNum); + int* firstNumBin = convertToBinary(firstNum); + int* secNumBin = convertToBinary(secNum); + printf("Первое число: "); + for (int j = 0; j < 8; j++) { + printf("%d", firstNumBin[j]); + } + printf(" Второе число: "); + for (int j = 0; j < 8; j++) { + printf("%d", secNumBin[j]); + } + printf("\n"); + int* sum = sumBinNumbers(firstNumBin, secNumBin); + printf("Двоичная сумма: "); + for (int j = 0; j < 8; j++) { + printf("%d", sum[j]); + } + printf("\n"); + int sumDec = 0; + sumDec = convertToDecimal(sum); + printf("Десятичная сумма: %d\n", sumDec); + printf("-----------------\n"); + + free(firstNumBin); + free(secNumBin); + free(sum); + return 0; +} \ No newline at end of file diff --git a/src/InternalDataRepresentation/lib1.h b/src/InternalDataRepresentation/lib1.h new file mode 100644 index 0000000..e0e574e --- /dev/null +++ b/src/InternalDataRepresentation/lib1.h @@ -0,0 +1,4 @@ +#pragma once + +// функция запуска тестов +void runTests(); \ No newline at end of file diff --git a/src/InternalDataRepresentation/lib2.h b/src/InternalDataRepresentation/lib2.h new file mode 100644 index 0000000..d67b536 --- /dev/null +++ b/src/InternalDataRepresentation/lib2.h @@ -0,0 +1,12 @@ +#pragma once +#include +#include + +void runTests(); + +typedef union { + double value; + uint64_t bits; +} Number; + +const char* parseDouble(Number num); \ No newline at end of file diff --git a/src/InternalDataRepresentation/testBinaryRepresentation.c b/src/InternalDataRepresentation/testBinaryRepresentation.c new file mode 100644 index 0000000..f8dc669 --- /dev/null +++ b/src/InternalDataRepresentation/testBinaryRepresentation.c @@ -0,0 +1,151 @@ +#include "lib1.h" +#include +#include +#include +#include + +int* simpleConvertionToBin(int n); +void addOne(int* binary); +void invertBits(int* binary); +int* convertToBinary(int n); +int* sumBinNumbers(int* fnum, int* snum); +int convertToDecimal(int* binary); + +bool testConverToDecimal() +{ + printf("Тестирование convertToDecimal...\n"); + int positive[] = { 0, 0, 0, 0, 0, 1, 0, 1 }; + assert((convertToDecimal(positive) == 5) && "Ошибка в функции перевода в десятичную СС положительного числа"); + int negative[] = { 1, 1, 1, 1, 1, 0, 1, 1 }; // -5 + assert((convertToDecimal(negative) == -5) && "Ошибка в функции перевода в десятичную СС отрицательного числа"); + int zero[] = { 0, 0, 0, 0, 0, 0, 0, 0 }; // 0 + assert((convertToDecimal(zero) == 0) && "Ошибка в функции перевода в десятичную СС нуля"); + printf("convertToDecimal тесты пройдены\n"); + return true; +} + +bool testSimpleConvertionToBin() +{ + printf("Тестирование simpleConvertiontoBin...\n"); + int* result = simpleConvertionToBin(5); + int expected[] = { 0, 0, 0, 0, 0, 1, 0, 1 }; + for (int i = 0; i < 8; i++) { + assert((result[i] == expected[i]) && "Ошибка в функции простого перевода в двоичную СС"); + } + free(result); + printf("simpleConvertiontoBin тесты пройдены\n"); + return true; +} + +bool testAddOne() +{ + printf("Тестирование addOne...\n"); + int test1[] = { 1, 1, 1, 1, 1, 0, 1, 0 }; // -6 в обратном коде + addOne(test1); + int expected1[] = { 1, 1, 1, 1, 1, 0, 1, 1 }; // -5 в доп. коде + for (int i = 0; i < 8; i++) { + assert((test1[i] == expected1[i]) && "Ошибка в функции добавления 1 в дв.сс."); + } + + int test2[] = { 0, 0, 0, 0, 0, 1, 1, 1 }; // 7 + addOne(test2); + int expected2[] = { 0, 0, 0, 0, 1, 0, 0, 0 }; // 8 + for (int i = 0; i < 8; i++) { + assert((test2[i] == expected2[i]) && "Ошибка в функции добавления 1 в дв.сс."); + } + printf("addOne тесты пройдены\n"); + return true; +} + +bool testInvertBits() +{ + printf("Тестирование invertBits...\n"); + + int zeros[] = { 0, 0, 0, 0, 0, 0, 0, 0 }; + invertBits(zeros); + int expected_ones[] = { 1, 1, 1, 1, 1, 1, 1, 1 }; + for (int i = 0; i < 8; i++) { + assert((zeros[i] == expected_ones[i]) && "Ошибка в функции инвертирования"); + } + + int mixed[] = { 0, 1, 0, 1, 0, 1, 0, 1 }; + invertBits(mixed); + int expected_mixed[] = { 1, 0, 1, 0, 1, 0, 1, 0 }; + for (int i = 0; i < 8; i++) { + assert((mixed[i] == expected_mixed[i]) && "Ошибка в функции инвертирования"); + } + printf("invertBits тесты пройдены\n"); + return true; +} + +bool testConvertToBinary() +{ + printf("Тестирование convertToBinary...\n"); + + int* result_positive = convertToBinary(10); + int expected_positive[] = { 0, 0, 0, 0, 1, 0, 1, 0 }; + for (int i = 0; i < 8; i++) { + assert((result_positive[i] == expected_positive[i]) && "Ошибка в функции полного перевода в двоичную сс положит. числа"); + } + free(result_positive); + + int* result_negative = convertToBinary(-10); + int expected_negative[] = { 1, 1, 1, 1, 0, 1, 1, 0 }; + for (int i = 0; i < 8; i++) { + assert((result_negative[i] == expected_negative[i]) && "Ошибка в функции полного перевода в двоичную сс отриц. числа"); + } + free(result_negative); + + int* result_zero = convertToBinary(0); + int expected_zero[] = { 0, 0, 0, 0, 0, 0, 0, 0 }; + for (int i = 0; i < 8; i++) { + assert((result_zero[i] == expected_zero[i]) && "Ошибка в функции полного перевода в двоичную сс нуля"); + } + free(result_zero); + printf("convertToBinary тесты пройдены\n"); + return true; +} + +bool testSumBinNumbers() +{ + printf("Тестирование sumBinNumbers...\n"); + int num1[] = { 0, 0, 0, 0, 0, 1, 0, 1 }; // 5 + int num2[] = { 0, 0, 0, 0, 0, 0, 1, 1 }; // 3 + int* result = sumBinNumbers(num1, num2); + int expected[] = { 0, 0, 0, 0, 1, 0, 0, 0 }; // 8 + for (int i = 0; i < 8; i++) { + assert((result[i] == expected[i]) && "Ошибка в функции побитового сложения двух положит. чисел"); + } + free(result); + + int num3[] = { 0, 0, 0, 0, 0, 1, 0, 1 }; // 5 + int num4[] = { 1, 1, 1, 1, 1, 0, 1, 1 }; // -5 + result = sumBinNumbers(num3, num4); + int expected_zero[] = { 0, 0, 0, 0, 0, 0, 0, 0 }; // 0 + for (int i = 0; i < 8; i++) { + assert((result[i] == expected_zero[i]) && "Ошибка в функции побитового сложения отриц. и полож. чисел"); + } + free(result); + + int num5[] = { 1, 1, 1, 1, 1, 0, 1, 1 }; // -5 + int num6[] = { 1, 1, 1, 1, 1, 1, 0, 1 }; // -3 + result = sumBinNumbers(num5, num6); + int expected_negative[] = { 1, 1, 1, 1, 1, 0, 0, 0 }; // -8 + for (int i = 0; i < 8; i++) { + assert((result[i] == expected_negative[i]) && "Ошибка в функции побитового сложения двух отриц. чисел"); + } + free(result); + printf("sumBinNumbers тесты пройдены\n"); + return true; +} +void runTests() +{ + printf("===!!! ЗАПУСК ТЕСТОВ ДЛЯ ЗАДАЧИ ДВОИЧНОЕ ПРЕДСТАВЛЕНИЕ !!!===\n\n"); + testConverToDecimal(); + testSimpleConvertionToBin(); + testAddOne(); + testInvertBits(); + testConvertToBinary(); + testSumBinNumbers(); + printf("\n===!!! ВСЕ ТЕСТЫ ПРОЙДЕНЫ УСПЕШНО! !!!===\n"); +} diff --git a/src/InternalDataRepresentation/testDoubleUnderMicroscope.c b/src/InternalDataRepresentation/testDoubleUnderMicroscope.c new file mode 100644 index 0000000..6c0adbb --- /dev/null +++ b/src/InternalDataRepresentation/testDoubleUnderMicroscope.c @@ -0,0 +1,63 @@ +#include "lib2.h" +#include +#include +#include +#include +#include + +bool testExample1() +{ + printf("Тестирование примера 1 (-2.5)\n"); + + Number num; + num.value = -2.5; + + const char* result = parseDouble(num); + assert((strcmp(result, "-1.25*2^1") == 0) && "Ошибка: парсинг числа -2.5 неверный\n"); + printf("Пример 1 тест пройден\n"); + return true; +} + +bool testExample2() +{ + printf("Тестирование примера 2 (12312.323)\n"); + + Number num; + num.value = 12312.323; + + const char* result = parseDouble(num); + assert((strcmp(result, "+1.50296911621093754*2^13") == 0) && "Ошибка: парсинг числа 12312.323 неверный\n"); + printf("Пример 2 тест пройден\n"); + return true; +} + +bool testSimpleNumbers() +{ + printf("Тестирование простых чисел\n"); + + Number num; + + num.value = 8.0; + const char* result = parseDouble(num); + assert((strcmp(result, "+1*2^3") == 0) && "Ошибка: парсинг числа 8.0 неверный\n"); + + num.value = 0.15625; + result = parseDouble(num); + assert((strcmp(result, "+1.25*2^-3") == 0) && "Ошибка: парсинг числа 0.15625 неверный\n"); + + num.value = 0.0; + result = parseDouble(num); + assert((strcmp(result, "+0*2^-1022") == 0) && "Ошибка: парсинг числа 0.0 неверный\n"); + + printf("тесты простых чисел пройдены\n"); + return true; +} + +void runTests() +{ + printf("===!!! ЗАПУСК ТЕСТОВ ДЛЯ ПАРСИНГА DOUBLE !!!===\n"); + testExample1(); + testExample2(); + testSimpleNumbers(); + printf("\n===!!! ВСЕ ТЕСТЫ ПРОЙДЕНЫ УСПЕШНО! !!!===\n"); +} \ No newline at end of file