-
Notifications
You must be signed in to change notification settings - Fork 0
ДЗ № 12.1 Двоичное представление, Шестаков Николай #16
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
2f7a6d3
66c5d82
fe328c2
1d1fcfa
c3cd06e
e68ab4f
443dcc5
5d02437
a85f0d6
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,245 @@ | ||
| --- | ||
| 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 | ||
| ... |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,6 @@ | ||
| version: 2 | ||
| updates: | ||
| - package-ecosystem: github-actions | ||
| directory: / | ||
| schedule: | ||
| interval: "weekly" |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,14 @@ | ||
| name: Build and lint | ||
|
|
||
| on: | ||
| - push | ||
| - pull_request | ||
|
|
||
| jobs: | ||
| check-format: | ||
| runs-on: ubuntu-latest | ||
| steps: | ||
| - uses: actions/checkout@v5 | ||
| - name: Check format | ||
| run: | | ||
| find . -path ./build -prune -o -type f -name '*.[c|h]' -print | xargs clang-format-18 --style=file --dry-run -Werror |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -55,4 +55,7 @@ Module.symvers | |
| Mkfile.old | ||
| dkms.conf | ||
|
|
||
| # CMake | ||
| build | ||
|
|
||
| # End of https://www.toptal.com/developers/gitignore/api/c | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,8 @@ | ||
| cmake_minimum_required(VERSION 3.25) | ||
| project(binary_representation C) | ||
|
|
||
| add_library(binlib src/binary_representation/binlib.c) | ||
|
|
||
| add_executable(binary_representation src/binary_representation/main.c) | ||
| target_link_libraries(binary_representation PRIVATE binlib) | ||
| target_compile_options(binary_representation PRIVATE -Wall -Wextra -pedantic) |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,97 @@ | ||
| #include "binlib.h" | ||
|
|
||
| #include <assert.h> | ||
| #include <stdint.h> | ||
| #include <stdio.h> | ||
| #include <stdlib.h> | ||
|
|
||
| char* decimalToBinary(int32_t decimal) | ||
| { | ||
| char* binary = malloc(32 * sizeof(char)); | ||
|
|
||
| for (int i = 0; i < 32; ++i) { | ||
| // Берём по биту, начиная с наименьшего разряда. | ||
| if ((1 << i) & decimal) { | ||
| binary[31 - i] = '1'; | ||
| } else { | ||
| binary[31 - i] = '0'; | ||
|
Comment on lines
+14
to
+17
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Ой, ну, так тоже можно, но не проще ли хранить прямо числа 0 и 1 в char (или вообще сделать `bool)? |
||
| } | ||
| } | ||
|
|
||
| return binary; | ||
| } | ||
|
|
||
| char* binarySum(char* binaryFirst, char* binarySecond) | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Здесь получается не очень честно, потому что у Вас может получиться двойка. А если перейти на язык |
||
| { | ||
| char* sum = malloc(32 * sizeof(char)); | ||
|
|
||
| // Берём каждый три чиселка, два из текущего разряда чисел и третье - остаток от предыдущего сложения. | ||
| int fromPrevious = 0; | ||
| for (int i = 31; i >= 0; --i) { | ||
| int fromFirst = binaryFirst[i] == '1' ? 1 : 0; | ||
| int fromSecond = binarySecond[i] == '1' ? 1 : 0; | ||
|
|
||
| switch (fromPrevious + fromFirst + fromSecond) { | ||
| case 0: | ||
| sum[i] = '0'; | ||
| fromPrevious = 0; | ||
| break; | ||
| case 1: | ||
| sum[i] = '1'; | ||
| fromPrevious = 0; | ||
| break; | ||
| case 2: | ||
| sum[i] = '0'; | ||
| fromPrevious = 1; | ||
| break; | ||
| case 3: | ||
| sum[i] = '1'; | ||
| fromPrevious = 1; | ||
| break; | ||
| } | ||
| } | ||
|
|
||
| return sum; | ||
| } | ||
|
|
||
| int32_t binaryToDecimal(char* binary) | ||
| { | ||
| int32_t decimal = 0; | ||
|
|
||
| // Переменная, которая показывает, что мы в данном случае считаем за непустой разряд. | ||
| char forOne = '1'; | ||
| if (binary[0] == '1') { | ||
| forOne = '0'; | ||
| } | ||
|
|
||
| for (int i = 1; i < 32; ++i) { | ||
| if (binary[i] == forOne) { | ||
| // Прибавляем к десятичной форме двойку в нужной степени. | ||
| decimal += (1 << (32 - i - 1)); | ||
| } | ||
| } | ||
|
|
||
| // Если число было отрицательным, то нужно прибавить 1 и умножить на -1 для правильного результата перевода из дополнительного кода. | ||
| if (binary[0] == '1') { | ||
| ++decimal; | ||
| decimal *= -1; | ||
|
Comment on lines
+75
to
+77
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Может просто вычесть 2^31? |
||
| } | ||
|
|
||
| return decimal; | ||
| } | ||
|
|
||
| void binaryPrint(char* binary) | ||
| { | ||
| // Ищем, где кончаются лидирующие нули и их не выводим. Если число 0, то выведется 0. | ||
| int firstOneIndex = 31; | ||
| for (int i = 0; i < 32; ++i) { | ||
| if (binary[i] == '1') { | ||
| firstOneIndex = i; | ||
| break; | ||
| } | ||
| } | ||
| for (int i = firstOneIndex; i < 32; ++i) { | ||
| printf("%c", binary[i]); | ||
| } | ||
| printf("\n"); | ||
| } | ||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Хорошо бы это обернуть в структуру, чтобы пользователь ненароком в другие функции не передал массив из 2 или 122 элементов