From bc1c0a906cbcdd65163558ac305b7e6f2d6edc28 Mon Sep 17 00:00:00 2001 From: Yana Kalsina Date: Thu, 27 Nov 2025 19:19:44 +0300 Subject: [PATCH 01/10] Add clang-format config --- .clang-format | 244 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 244 insertions(+) create mode 100644 .clang-format 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 From ef61cb3133675c7fdfd0cbdb155d3ae1655bb9e8 Mon Sep 17 00:00:00 2001 From: Yana Kalsina Date: Thu, 27 Nov 2025 21:39:21 +0300 Subject: [PATCH 02/10] first version of binary representation --- CMakeLists.txt | 7 + CMakelists.txt | 7 + .../binaryRepresentation.c | 129 ++++++++++++++++++ 3 files changed, 143 insertions(+) create mode 100644 CMakeLists.txt create mode 100644 CMakelists.txt create mode 100644 src/InternalDataRepresentation/binaryRepresentation.c 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/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/binaryRepresentation.c b/src/InternalDataRepresentation/binaryRepresentation.c new file mode 100644 index 0000000..916612d --- /dev/null +++ b/src/InternalDataRepresentation/binaryRepresentation.c @@ -0,0 +1,129 @@ +#include +#include +#include + +int* simpleConvertion(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 = simpleConvertion(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 power(int base, int exponent) +{ + int result = 1; + for (int i = 0; i < exponent; i++) { + result *= base; + } + return result; +} + +int convertToDecimal(int* binary) +{ + int decimal = 0; + int power = 128; // 2⁷ для старшего бита + + for (int i = 0; i < 8; i++) { + if (binary[i] == 1) { + decimal += power; + } + power /= 2; // Уменьшаем степень двойки + } + return decimal; +} + +int main(void) +{ + 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", &sum); + printf("-----------------\n"); + + free(firstNumBin); + free(secNumBin); + free(sum); + return 0; +} \ No newline at end of file From 8f5c7297754cbbdf8087eb255a3c6e0f27113311 Mon Sep 17 00:00:00 2001 From: Yana Kalsina Date: Fri, 28 Nov 2025 14:54:15 +0300 Subject: [PATCH 03/10] Write final version on binary representation --- .../binaryRepresentation.c | 30 +++++++++++-------- 1 file changed, 17 insertions(+), 13 deletions(-) diff --git a/src/InternalDataRepresentation/binaryRepresentation.c b/src/InternalDataRepresentation/binaryRepresentation.c index 916612d..8bc4f2e 100644 --- a/src/InternalDataRepresentation/binaryRepresentation.c +++ b/src/InternalDataRepresentation/binaryRepresentation.c @@ -2,6 +2,11 @@ #include #include +/* +Я выбрала 8ми битное представление чисел, сответственно, +диапазон выбора числа огранчен. от - 128 до 127 - безопасный диапазон. +*/ + int* simpleConvertion(int n) { int* binary = calloc(8, sizeof(int)); @@ -70,25 +75,24 @@ int* sumBinNumbers(int* fnum, int* snum) return sum; } -int power(int base, int exponent) -{ - int result = 1; - for (int i = 0; i < exponent; i++) { - result *= base; - } - return result; -} - int convertToDecimal(int* binary) { + bool isNegative = false; + if (binary[1] == 1) { + invertBits(binary); + addOne(binary); + isNegative = true; + } int decimal = 0; - int power = 128; // 2⁷ для старшего бита - + int power = 128; for (int i = 0; i < 8; i++) { if (binary[i] == 1) { decimal += power; } - power /= 2; // Уменьшаем степень двойки + power /= 2; + } + if (isNegative) { + return -decimal; } return decimal; } @@ -119,7 +123,7 @@ int main(void) printf("\n"); int sumDec = 0; sumDec = convertToDecimal(sum); - printf("Десятичная сумма: %d\n", &sum); + printf("Десятичная сумма: %d\n", sumDec); printf("-----------------\n"); free(firstNumBin); From 9daff4d72fa892cfce59c9e8ba33b3ccc8736593 Mon Sep 17 00:00:00 2001 From: Yana Kalsina Date: Fri, 28 Nov 2025 15:30:29 +0300 Subject: [PATCH 04/10] Write tests for binaryRepresentation task --- .../testBinaryRepresentation.c | 137 ++++++++++++++++++ 1 file changed, 137 insertions(+) create mode 100644 src/InternalDataRepresentation/testBinaryRepresentation.c diff --git a/src/InternalDataRepresentation/testBinaryRepresentation.c b/src/InternalDataRepresentation/testBinaryRepresentation.c new file mode 100644 index 0000000..198d141 --- /dev/null +++ b/src/InternalDataRepresentation/testBinaryRepresentation.c @@ -0,0 +1,137 @@ +#include +#include +#include + +void 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"); +} + +void 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"); +} + +void 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"); +} + +// Тест функции invertBits +void 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"); +} + +void 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"); +} + +void 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"); +} +void runTests() +{ + printf("===!!! ЗАПУСК ТЕСТОВ ДЛЯ ЗАДАЧИ ДВОИЧНОЕ ПРЕДСТАВЛЕНИЕ !!!===\n\n"); + testConverToDecimal(); + testSimpleConvertionToBinary(); + testAddOne(); + testInvertBits(); + testConvertToBinary(); + testSumBinNumbers(); + printf("\n===!!! ВСЕ ТЕСТЫ ПРОЙДЕНЫ УСПЕШНО! !!!===\n"); +} From 73ffea6d424c59874f3a13563ba5604dbb033648 Mon Sep 17 00:00:00 2001 From: Yana Kalsina Date: Fri, 28 Nov 2025 15:30:59 +0300 Subject: [PATCH 05/10] Add arguments to main func --- .../binaryRepresentation.c | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/src/InternalDataRepresentation/binaryRepresentation.c b/src/InternalDataRepresentation/binaryRepresentation.c index 8bc4f2e..4c6bfde 100644 --- a/src/InternalDataRepresentation/binaryRepresentation.c +++ b/src/InternalDataRepresentation/binaryRepresentation.c @@ -4,10 +4,10 @@ /* Я выбрала 8ми битное представление чисел, сответственно, -диапазон выбора числа огранчен. от - 128 до 127 - безопасный диапазон. +диапазон выбора числа огранчен. от [-128 , 127] - безопасный диапазон. */ -int* simpleConvertion(int n) +int* simpleConvertionToBin(int n) { int* binary = calloc(8, sizeof(int)); int i = 7; @@ -54,7 +54,7 @@ int* convertToBinary(int n) isNegative = true; n = -n; } - int* binary = simpleConvertion(n); + int* binary = simpleConvertionToBin(n); if (isNegative) { invertBits(binary); addOne(binary); @@ -97,8 +97,12 @@ int convertToDecimal(int* binary) return decimal; } -int main(void) +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"); From 39dd957bb2240b7586c066bc19be6d7223512929 Mon Sep 17 00:00:00 2001 From: Yana Kalsina Date: Fri, 28 Nov 2025 15:34:15 +0300 Subject: [PATCH 06/10] Change function's type to bool --- .../testBinaryRepresentation.c | 20 ++++++++++++------- 1 file changed, 13 insertions(+), 7 deletions(-) diff --git a/src/InternalDataRepresentation/testBinaryRepresentation.c b/src/InternalDataRepresentation/testBinaryRepresentation.c index 198d141..82cf3fb 100644 --- a/src/InternalDataRepresentation/testBinaryRepresentation.c +++ b/src/InternalDataRepresentation/testBinaryRepresentation.c @@ -1,8 +1,9 @@ #include +#include #include #include -void testConverToDecimal() +bool testConverToDecimal() { printf("Тестирование convertToDecimal...\n"); int positive[] = { 0, 0, 0, 0, 0, 1, 0, 1 }; @@ -12,9 +13,10 @@ void testConverToDecimal() int zero[] = { 0, 0, 0, 0, 0, 0, 0, 0 }; // 0 assert((convertToDecimal(zero) == 0) && "Ошибка в функции перевода в десятичную СС нуля"); printf("convertToDecimal тесты пройдены\n"); + return true; } -void testSimpleConvertionToBin() +bool testSimpleConvertionToBin() { printf("Тестирование simpleConvertiontoBin...\n"); int* result = simpleConvertiontoBin(5); @@ -24,9 +26,10 @@ void testSimpleConvertionToBin() } free(result); printf("simpleConvertiontoBin тесты пройдены\n"); + return true; } -void testAddOne() +bool testAddOne() { printf("Тестирование addOne...\n"); int test1[] = { 1, 1, 1, 1, 1, 0, 1, 0 }; // -6 в обратном коде @@ -43,10 +46,10 @@ void testAddOne() assert((test2[i] == expected2[i]) && "Ошибка в функции добавления 1 в дв.сс."); } printf("addOne тесты пройдены\n"); + return true; } -// Тест функции invertBits -void testInvertBits() +bool testInvertBits() { printf("Тестирование invertBits...\n"); @@ -64,9 +67,10 @@ void testInvertBits() assert((mixed[i] == expected_mixed[i]) && "Ошибка в функции инвертирования"); } printf("invertBits тесты пройдены\n"); + return true; } -void testConvertToBinary() +bool testConvertToBinary() { printf("Тестирование convertToBinary...\n"); @@ -91,9 +95,10 @@ void testConvertToBinary() } free(result_zero); printf("convertToBinary тесты пройдены\n"); + return true; } -void testSumBinNumbers() +bool testSumBinNumbers() { printf("Тестирование sumBinNumbers...\n"); int num1[] = { 0, 0, 0, 0, 0, 1, 0, 1 }; // 5 @@ -123,6 +128,7 @@ void testSumBinNumbers() } free(result); printf("sumBinNumbers тесты пройдены\n"); + return true; } void runTests() { From eff3b65e043be83834b7bff41d823edeec8880a5 Mon Sep 17 00:00:00 2001 From: Yana Kalsina Date: Fri, 28 Nov 2025 15:35:07 +0300 Subject: [PATCH 07/10] Change CmakeLists --- src/InternalDataRepresentation/CMakeLists.txt | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 src/InternalDataRepresentation/CMakeLists.txt diff --git a/src/InternalDataRepresentation/CMakeLists.txt b/src/InternalDataRepresentation/CMakeLists.txt new file mode 100644 index 0000000..913b1ae --- /dev/null +++ b/src/InternalDataRepresentation/CMakeLists.txt @@ -0,0 +1,3 @@ +add_executable(binaryRepresentation +binaryRepresentation.c, +testBinaryRepresentation.c) \ No newline at end of file From e2ead6a3f0e1b7006685bbb5a8a569fc354248a1 Mon Sep 17 00:00:00 2001 From: Yana Kalsina Date: Fri, 28 Nov 2025 15:38:04 +0300 Subject: [PATCH 08/10] Nado tak --- CMakeLists.txt | 2 ++ src/InternalDataRepresentation/CMakeLists.txt | 4 +--- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index da6e315..9ea9b95 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -4,4 +4,6 @@ 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/src/InternalDataRepresentation/CMakeLists.txt b/src/InternalDataRepresentation/CMakeLists.txt index 913b1ae..414e5f8 100644 --- a/src/InternalDataRepresentation/CMakeLists.txt +++ b/src/InternalDataRepresentation/CMakeLists.txt @@ -1,3 +1 @@ -add_executable(binaryRepresentation -binaryRepresentation.c, -testBinaryRepresentation.c) \ No newline at end of file +add_executable(binaryRepresentation binaryRepresentation.c testBinaryRepresentation.c) \ No newline at end of file From 4ac13f38932646f1c632edca612cfa5806af808e Mon Sep 17 00:00:00 2001 From: Yana Kalsina Date: Fri, 28 Nov 2025 15:51:02 +0300 Subject: [PATCH 09/10] Connected all the files --- src/InternalDataRepresentation/CMakeLists.txt | 2 +- .../binaryRepresentation.c | 1 + src/InternalDataRepresentation/lib1.h | 4 ++++ .../testBinaryRepresentation.c | 12 ++++++++++-- 4 files changed, 16 insertions(+), 3 deletions(-) create mode 100644 src/InternalDataRepresentation/lib1.h diff --git a/src/InternalDataRepresentation/CMakeLists.txt b/src/InternalDataRepresentation/CMakeLists.txt index 414e5f8..b755f11 100644 --- a/src/InternalDataRepresentation/CMakeLists.txt +++ b/src/InternalDataRepresentation/CMakeLists.txt @@ -1 +1 @@ -add_executable(binaryRepresentation binaryRepresentation.c testBinaryRepresentation.c) \ No newline at end of file +add_executable(binaryRepresentation binaryRepresentation.c testBinaryRepresentation.c) diff --git a/src/InternalDataRepresentation/binaryRepresentation.c b/src/InternalDataRepresentation/binaryRepresentation.c index 4c6bfde..900aebc 100644 --- a/src/InternalDataRepresentation/binaryRepresentation.c +++ b/src/InternalDataRepresentation/binaryRepresentation.c @@ -1,3 +1,4 @@ +#include "lib1.h" #include #include #include 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/testBinaryRepresentation.c b/src/InternalDataRepresentation/testBinaryRepresentation.c index 82cf3fb..f8dc669 100644 --- a/src/InternalDataRepresentation/testBinaryRepresentation.c +++ b/src/InternalDataRepresentation/testBinaryRepresentation.c @@ -1,8 +1,16 @@ +#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"); @@ -19,7 +27,7 @@ bool testConverToDecimal() bool testSimpleConvertionToBin() { printf("Тестирование simpleConvertiontoBin...\n"); - int* result = simpleConvertiontoBin(5); + 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]) && "Ошибка в функции простого перевода в двоичную СС"); @@ -134,7 +142,7 @@ void runTests() { printf("===!!! ЗАПУСК ТЕСТОВ ДЛЯ ЗАДАЧИ ДВОИЧНОЕ ПРЕДСТАВЛЕНИЕ !!!===\n\n"); testConverToDecimal(); - testSimpleConvertionToBinary(); + testSimpleConvertionToBin(); testAddOne(); testInvertBits(); testConvertToBinary(); From 9a09f7d175b5ca971858f932ad820e87ae75d954 Mon Sep 17 00:00:00 2001 From: Yana Kalsina Date: Mon, 1 Dec 2025 22:14:00 +0300 Subject: [PATCH 10/10] Add solving for second task --- src/InternalDataRepresentation/CMakeLists.txt | 1 + .../DoubleUnderMicroscope.c | 55 ++++++++++++++++ .../binaryRepresentation.c | 1 + src/InternalDataRepresentation/lib2.h | 12 ++++ .../testDoubleUnderMicroscope.c | 63 +++++++++++++++++++ 5 files changed, 132 insertions(+) create mode 100644 src/InternalDataRepresentation/DoubleUnderMicroscope.c create mode 100644 src/InternalDataRepresentation/lib2.h create mode 100644 src/InternalDataRepresentation/testDoubleUnderMicroscope.c diff --git a/src/InternalDataRepresentation/CMakeLists.txt b/src/InternalDataRepresentation/CMakeLists.txt index b755f11..28c81e0 100644 --- a/src/InternalDataRepresentation/CMakeLists.txt +++ b/src/InternalDataRepresentation/CMakeLists.txt @@ -1 +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 index 900aebc..7b08bc0 100644 --- a/src/InternalDataRepresentation/binaryRepresentation.c +++ b/src/InternalDataRepresentation/binaryRepresentation.c @@ -2,6 +2,7 @@ #include #include #include +#include /* Я выбрала 8ми битное представление чисел, сответственно, 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/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