bin-dec-conversions 0.1.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of bin-dec-conversions might be problematic. Click here for more details.

@@ -0,0 +1,3 @@
1
+ from .bin_dec_conversions import binary_to_decimal, decimal_to_binary
2
+
3
+ __all__ = ["binary_to_decimal", "decimal_to_binary"]
@@ -0,0 +1,32 @@
1
+ import re
2
+
3
+
4
+ def binary_to_decimal(binary: str) -> int:
5
+ if not re.fullmatch(r"[01]+", binary):
6
+ raise ValueError("Binary must contain only 0s and 1s")
7
+
8
+ decimal = 0
9
+ for i, bit in enumerate(reversed(binary)):
10
+ if bit == "1":
11
+ decimal += 2**i
12
+
13
+ return decimal
14
+
15
+
16
+ def decimal_to_binary(decimal: int, width: int = 0) -> str:
17
+ """Convert a non-negative integer to binary, left-padded with zeros to `width`."""
18
+ if decimal < 0:
19
+ raise ValueError("Decimal must be non-negative")
20
+ if width < 0:
21
+ raise ValueError("Width must be non-negative")
22
+
23
+ if decimal == 0:
24
+ bits = "0"
25
+ else:
26
+ digits = []
27
+ while decimal > 0:
28
+ digits.append(str(decimal % 2))
29
+ decimal //= 2
30
+ bits = "".join(reversed(digits))
31
+
32
+ return bits.zfill(width)
@@ -0,0 +1,107 @@
1
+ import argparse
2
+ import sys
3
+
4
+ import questionary
5
+
6
+ from bin_dec_conversions import binary_to_decimal, decimal_to_binary
7
+
8
+
9
+ def prompt_binary_to_decimal() -> None:
10
+ while True:
11
+ binary = input("Insert a binary number: ").strip()
12
+ try:
13
+ decimal = binary_to_decimal(binary)
14
+ except ValueError as e:
15
+ print(e)
16
+ else:
17
+ print(f"The decimal equivalent of {binary} is {decimal}")
18
+ return
19
+
20
+
21
+ def prompt_decimal_to_binary() -> None:
22
+ while True:
23
+ raw = input("Insert a decimal number: ").strip()
24
+ try:
25
+ decimal = int(raw)
26
+ except ValueError:
27
+ print("Insert a whole number!")
28
+ continue
29
+
30
+ try:
31
+ binary = decimal_to_binary(decimal)
32
+ except ValueError as e:
33
+ print(e)
34
+ else:
35
+ print(f"The binary equivalent of {decimal} is {binary}")
36
+ return
37
+
38
+
39
+ def interactive_menu():
40
+ choice = questionary.select(
41
+ "Which operation do you want to perform?",
42
+ choices=[
43
+ "From binary to decimal",
44
+ "From decimal to binary",
45
+ ],
46
+ ).ask()
47
+
48
+ match choice:
49
+ case "From binary to decimal":
50
+ prompt_binary_to_decimal()
51
+ case "From decimal to binary":
52
+ prompt_decimal_to_binary()
53
+
54
+
55
+ def create_parser():
56
+ parser = argparse.ArgumentParser(
57
+ prog="bin-dec-conversions",
58
+ description="Convert between binary and decimal. "
59
+ "Run with no arguments for interactive mode.",
60
+ )
61
+ group = parser.add_mutually_exclusive_group()
62
+ group.add_argument(
63
+ "-d",
64
+ "--to-decimal",
65
+ metavar="BINARY",
66
+ help="convert a binary string to decimal",
67
+ )
68
+ group.add_argument(
69
+ "-b",
70
+ "--to-binary",
71
+ metavar="DECIMAL",
72
+ type=int,
73
+ help="convert a non-negative integer to binary",
74
+ )
75
+ parser.add_argument(
76
+ "-w",
77
+ "--width",
78
+ type=int,
79
+ default=0,
80
+ help="zero-pad the binary output to this width (only with --to-binary)",
81
+ )
82
+ return parser
83
+
84
+
85
+ def main(argv: list[str] | None = None) -> int:
86
+ parser = create_parser()
87
+ args = parser.parse_args(argv)
88
+
89
+ if args.width and args.to_binary is None:
90
+ parser.error("--width can only be used with --to-binary")
91
+
92
+ try:
93
+ if args.to_decimal is not None:
94
+ print(binary_to_decimal(args.to_decimal))
95
+ elif args.to_binary is not None:
96
+ print(decimal_to_binary(args.to_binary, args.width))
97
+ else:
98
+ interactive_menu()
99
+ except ValueError as e:
100
+ print(e, file=sys.stderr)
101
+ return 1
102
+
103
+ return 0
104
+
105
+
106
+ if __name__ == "__main__":
107
+ raise SystemError(main())
@@ -0,0 +1,144 @@
1
+ Metadata-Version: 2.4
2
+ Name: bin-dec-conversions
3
+ Version: 0.1.1
4
+ Summary: Convert between binary and decimal from Python or the command line
5
+ Author-email: Marco Salvatore Tornabene <tornabenemarco56@gmail.com>
6
+ License-Expression: MIT
7
+ Project-URL: Repository, https://github.com/JustM4rk123/bin_dec_conversions
8
+ Keywords: binary,decimal,conversion
9
+ Requires-Python: >=3.10
10
+ Description-Content-Type: text/markdown
11
+ License-File: LICENSE
12
+ Requires-Dist: questionary
13
+ Dynamic: license-file
14
+
15
+ # bin-dec-conversions
16
+
17
+ Convert binary numbers to decimal and decimal integers to binary with a small
18
+ Python library and command-line interface.
19
+
20
+ ## Features
21
+
22
+ - Convert a non-empty string of `0`s and `1`s to a decimal integer.
23
+ - Convert a non-negative integer to binary, optionally padding the output to a
24
+ minimum width.
25
+ - Use the interactive menu or run a conversion directly with command-line
26
+ options.
27
+ - Validate inputs and report invalid values.
28
+
29
+ ## Requirements
30
+
31
+ - Python 3.10 or newer.
32
+ - [`questionary`](https://github.com/tmbo/questionary) is installed automatically
33
+ and is used by the interactive menu.
34
+
35
+ ## Installation
36
+
37
+ Clone the repository and install the package:
38
+
39
+ ```bash
40
+ git clone https://github.com/JustM4rk123/bin_dec_conversions.git
41
+ cd bin_dec_conversions
42
+ python -m pip install .
43
+ ```
44
+
45
+ ## Usage
46
+
47
+ ### Command line
48
+
49
+ Run without arguments to open the interactive menu. Select a conversion with
50
+ the arrow keys and Enter, then enter a value:
51
+
52
+ ```text
53
+ Which operation do you want to perform? From binary to decimal
54
+ Insert a binary number: 1010
55
+ The decimal equivalent of 1010 is 10
56
+ ```
57
+
58
+ In interactive mode, invalid input displays an error and prompts again. You can
59
+ also convert directly with flags:
60
+
61
+ ```console
62
+ $ bin-dec-conversions --to-decimal 1010
63
+ 10
64
+
65
+ $ bin-dec-conversions --to-binary 10
66
+ 1010
67
+
68
+ $ bin-dec-conversions --to-binary 10 --width 8
69
+ 00001010
70
+ ```
71
+
72
+ Use `-d` for `--to-decimal`, `-b` for `--to-binary`, and `-w` for `--width`.
73
+ The conversion options are mutually exclusive. The width option zero-pads
74
+ binary output to at least the requested number of characters; it never
75
+ truncates a result. Invalid flag-mode input is reported as an error and exits
76
+ with a non-zero status.
77
+
78
+ ### Python library
79
+
80
+ The public API provides two functions:
81
+
82
+ - `binary_to_decimal(binary: str) -> int` converts a non-empty string containing
83
+ only `0`s and `1`s. It raises `ValueError` for empty strings or other
84
+ characters.
85
+ - `decimal_to_binary(decimal: int, width: int = 0) -> str` converts a
86
+ non-negative integer to binary, left-padded with zeros to at least `width`
87
+ characters. It raises `ValueError` if the value or width is negative.
88
+
89
+ ```python
90
+ from bin_dec_conversions import binary_to_decimal, decimal_to_binary
91
+
92
+ binary_to_decimal("1010") # 10
93
+ binary_to_decimal("0001") # 1 (leading zeros are allowed)
94
+
95
+ decimal_to_binary(10) # "1010"
96
+ decimal_to_binary(5, width=8) # "00000101"
97
+ decimal_to_binary(255, width=4) # "11111111" (never truncated)
98
+ ```
99
+
100
+ ## Development
101
+
102
+ Create a virtual environment and install the project in editable mode with its
103
+ development dependencies:
104
+
105
+ ```bash
106
+ python -m venv .venv
107
+ source .venv/bin/activate # Windows: .venv\Scripts\activate
108
+ python -m pip install -e . --group dev # requires pip 25.1+
109
+ ```
110
+
111
+ Alternatively, with [uv](https://docs.astral.sh/uv/), run `uv sync`. The `dev`
112
+ dependency group includes `pytest`, `black`, and `ruff`.
113
+
114
+ Run the tests:
115
+
116
+ ```bash
117
+ python -m pytest
118
+ ```
119
+
120
+ Format and lint:
121
+
122
+ ```bash
123
+ black .
124
+ ruff check .
125
+ ```
126
+
127
+ ## Project structure
128
+
129
+ ```text
130
+ bin_dec_conversions/
131
+ ├── pyproject.toml
132
+ ├── src/
133
+ │ └── bin_dec_conversions/
134
+ │ ├── __init__.py # public API
135
+ │ ├── bin_dec_conversions.py # conversion functions
136
+ │ └── cli.py # command-line interface
137
+ └── tests/
138
+ ├── test_bin_dec_conversion.py
139
+ └── test_cli.py
140
+ ```
141
+
142
+ ## License
143
+
144
+ This project is licensed under the MIT License. See [LICENSE](LICENSE).
@@ -0,0 +1,9 @@
1
+ bin_dec_conversions/__init__.py,sha256=R8WfnORM39P_AF4mZZ1SeDww8jE5giwubvHGIUvYrLw,124
2
+ bin_dec_conversions/bin_dec_conversions.py,sha256=MStJDemHowK8k1M12t0B69Shz2MsrFLJR7FvqwoB0I4,834
3
+ bin_dec_conversions/cli.py,sha256=Igs1PMEaZ-G5sVhnKlsdcYCRRLmjRLuEW1iYlc0Jx4k,2736
4
+ bin_dec_conversions-0.1.1.dist-info/licenses/LICENSE,sha256=YfFS1t3oeYHfAswn3mkASw5-g_S3lj7-Qk9iZH1ZPTY,1075
5
+ bin_dec_conversions-0.1.1.dist-info/METADATA,sha256=qIs4NLpNWNwQR6s_aTuS-hq_XDWJ0HCLoO58ZDOAMtU,3983
6
+ bin_dec_conversions-0.1.1.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
7
+ bin_dec_conversions-0.1.1.dist-info/entry_points.txt,sha256=KcOQCt_0BsbPt6Xr3-sykbZ4p8fLiLKvx83FaocFHY0,69
8
+ bin_dec_conversions-0.1.1.dist-info/top_level.txt,sha256=Jvs-J_e3y4uJKoPbaEzOrbBWSZaOHlxdZH2dSpH3K5k,20
9
+ bin_dec_conversions-0.1.1.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ bin-dec-conversions = bin_dec_conversions.cli:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Marco S. Tornabene
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ bin_dec_conversions