|
1 |
| -# patch-255 |
2 |
| -decimal_accuracy = 7 |
3 |
| - |
4 |
| - |
5 |
| -def dtbconverter(num): |
6 |
| - whole = [] |
7 |
| - fractional = ["."] |
8 |
| - |
9 |
| - decimal = round(num % 1, decimal_accuracy) |
10 |
| - w_num = int(num) |
11 |
| - |
12 |
| - i = 0 |
13 |
| - while decimal != 1 and i < decimal_accuracy: |
14 |
| - decimal = decimal * 2 |
15 |
| - fractional.append(int(decimal // 1)) |
16 |
| - decimal = round(decimal % 1, decimal_accuracy) |
17 |
| - if decimal == 0: |
18 |
| - break |
19 |
| - i += 1 |
20 |
| - |
21 |
| - while w_num != 0: |
22 |
| - whole.append(w_num % 2) |
23 |
| - w_num = w_num // 2 |
24 |
| - whole.reverse() |
25 |
| - |
26 |
| - i = 0 |
27 |
| - while i < len(whole): |
28 |
| - print(whole[i], end="") |
29 |
| - i += 1 |
30 |
| - i = 0 |
31 |
| - while i < len(fractional): |
32 |
| - print(fractional[i], end="") |
33 |
| - i += 1 |
34 |
| - |
35 |
| - |
36 |
| -number = float(input("Enter Any base-10 Number: ")) |
37 |
| - |
38 |
| -dtbconverter(number) |
39 |
| - |
40 |
| - |
41 |
| -# i think this code have not proper comment and noe this is easy to understand |
42 | 1 | """
|
43 |
| -======= |
44 |
| -Program: Decimal to Binary converter. |
45 |
| -
|
46 |
| -THis program accepts fractional values, the accuracy can be set below: |
| 2 | +Decimal to Binary Converter |
| 3 | +
|
| 4 | +This program converts base-10 decimal numbers (including fractional values) |
| 5 | +to their binary representation. The conversion handles both integer and |
| 6 | +fractional parts with configurable precision. |
| 7 | +
|
| 8 | +Features: |
| 9 | +- Converts both integer and fractional decimal numbers to binary |
| 10 | +- Configurable precision for fractional part conversion |
| 11 | +- Handles negative numbers |
| 12 | +- Type annotations for better code clarity |
| 13 | +- Robust error handling for various input scenarios |
47 | 14 | """
|
48 | 15 |
|
49 |
| - |
50 |
| -# Function to convert decimal number |
51 |
| -# to binary using recursion |
52 |
| -def DecimalToBinary(num): |
53 |
| - if num > 1: |
54 |
| - DecimalToBinary(num // 2) |
55 |
| - print(num % 2, end="") |
| 16 | +decimal_accuracy = 7 # Precision for fractional part conversion |
| 17 | + |
| 18 | + |
| 19 | +def decimal_to_binary(number: float) -> str: |
| 20 | + """ |
| 21 | + Convert a decimal number to its binary representation. |
| 22 | + |
| 23 | + Args: |
| 24 | + number (float): The base-10 number to convert to binary |
| 25 | + |
| 26 | + Returns: |
| 27 | + str: Binary representation of the input number |
| 28 | + """ |
| 29 | + # Handle special cases |
| 30 | + if number == 0: |
| 31 | + return "0" |
| 32 | + |
| 33 | + # Handle negative numbers |
| 34 | + is_negative = number < 0 |
| 35 | + number = abs(number) |
| 36 | + |
| 37 | + # Separate integer and fractional parts |
| 38 | + integer_part = int(number) |
| 39 | + fractional_part = round(number - integer_part, decimal_accuracy) |
| 40 | + |
| 41 | + # Convert integer part to binary |
| 42 | + integer_binary = _convert_integer_part(integer_part) |
| 43 | + |
| 44 | + # Convert fractional part to binary |
| 45 | + fractional_binary = _convert_fractional_part(fractional_part) |
| 46 | + |
| 47 | + # Combine parts and add sign if needed |
| 48 | + result = integer_binary + fractional_binary |
| 49 | + return f"-{result}" if is_negative else result |
| 50 | + |
| 51 | + |
| 52 | +def _convert_integer_part(integer: int) -> str: |
| 53 | + """ |
| 54 | + Convert integer part to binary using division method. |
| 55 | + |
| 56 | + Args: |
| 57 | + integer (int): Integer part of the number |
| 58 | + |
| 59 | + Returns: |
| 60 | + str: Binary representation of the integer part |
| 61 | + """ |
| 62 | + if integer == 0: |
| 63 | + return "0" |
| 64 | + |
| 65 | + binary_digits = [] |
| 66 | + num = integer |
| 67 | + |
| 68 | + while num > 0: |
| 69 | + binary_digits.append(str(num % 2)) # Get remainder |
| 70 | + num = num // 2 # Integer division |
| 71 | + |
| 72 | + # Reverse the list to get correct binary order |
| 73 | + binary_digits.reverse() |
| 74 | + return "".join(binary_digits) |
| 75 | + |
| 76 | + |
| 77 | +def _convert_fractional_part(fraction: float) -> str: |
| 78 | + """ |
| 79 | + Convert fractional part to binary using multiplication method. |
| 80 | + |
| 81 | + Args: |
| 82 | + fraction (float): Fractional part of the number (0 <= fraction < 1) |
| 83 | + |
| 84 | + Returns: |
| 85 | + str: Binary representation of the fractional part |
| 86 | + """ |
| 87 | + if fraction == 0: |
| 88 | + return "" |
| 89 | + |
| 90 | + binary_digits = ["."] |
| 91 | + current_fraction = fraction |
| 92 | + iterations = 0 |
| 93 | + |
| 94 | + # Convert fractional part until it becomes 0 or reaches maximum precision |
| 95 | + while current_fraction > 0 and iterations < decimal_accuracy: |
| 96 | + # Multiply by 2 and take integer part |
| 97 | + current_fraction *= 2 |
| 98 | + integer_part = int(current_fraction) |
| 99 | + binary_digits.append(str(integer_part)) |
| 100 | + |
| 101 | + # Keep only the fractional part for next iteration |
| 102 | + current_fraction -= integer_part |
| 103 | + current_fraction = round(current_fraction, decimal_accuracy) |
| 104 | + iterations += 1 |
| 105 | + |
| 106 | + return "".join(binary_digits) |
| 107 | + |
| 108 | + |
| 109 | +def decimal_to_binary_recursive(number: int) -> str: |
| 110 | + """ |
| 111 | + Alternative recursive implementation for integer conversion only. |
| 112 | + |
| 113 | + Note: This version only works with integers and doesn't handle fractional parts. |
| 114 | + |
| 115 | + Args: |
| 116 | + number (int): Integer number to convert to binary |
| 117 | + |
| 118 | + Returns: |
| 119 | + str: Binary representation of the integer |
| 120 | + """ |
| 121 | + if number > 1: |
| 122 | + return decimal_to_binary_recursive(number // 2) + str(number % 2) |
| 123 | + return str(number) |
| 124 | + |
| 125 | + |
| 126 | +def get_user_input() -> float: |
| 127 | + """ |
| 128 | + Safely get user input with comprehensive error handling. |
| 129 | + |
| 130 | + Returns: |
| 131 | + float: Validated decimal number from user input |
| 132 | + |
| 133 | + Raises: |
| 134 | + KeyboardInterrupt: If user interrupts the program |
| 135 | + EOFError: If no input is available (non-interactive environment) |
| 136 | + """ |
| 137 | + max_attempts = 3 |
| 138 | + |
| 139 | + for attempt in range(max_attempts): |
| 140 | + try: |
| 141 | + user_input = input("Enter any base-10 number (or 'quit' to exit): ").strip() |
| 142 | + |
| 143 | + if user_input.lower() in ['quit', 'exit', 'q']: |
| 144 | + print("Goodbye!") |
| 145 | + exit(0) |
| 146 | + |
| 147 | + return float(user_input) |
| 148 | + |
| 149 | + except ValueError: |
| 150 | + print(f"Error: '{user_input}' is not a valid number. Please try again.") |
| 151 | + if attempt < max_attempts - 1: |
| 152 | + print(f"{max_attempts - attempt - 1} attempts remaining.") |
| 153 | + else: |
| 154 | + print("Maximum attempts reached. Using default value 0.") |
| 155 | + return 0.0 |
| 156 | + except (EOFError, KeyboardInterrupt): |
| 157 | + raise |
| 158 | + |
| 159 | + |
| 160 | +def main() -> None: |
| 161 | + """Main function to run the decimal to binary converter.""" |
| 162 | + print("=== Decimal to Binary Converter ===") |
| 163 | + print(f"Fractional precision: {decimal_accuracy} bits") |
| 164 | + print("Enter 'quit' to exit the program") |
| 165 | + print("-" * 40) |
| 166 | + |
| 167 | + try: |
| 168 | + while True: |
| 169 | + try: |
| 170 | + # Get input from user |
| 171 | + number = get_user_input() |
| 172 | + |
| 173 | + # Convert to binary using main method |
| 174 | + binary_result = decimal_to_binary(number) |
| 175 | + |
| 176 | + # Display results |
| 177 | + print(f"\nDecimal number: {number}") |
| 178 | + print(f"Binary representation: {binary_result}") |
| 179 | + |
| 180 | + # For integer inputs, show recursive method as well |
| 181 | + if number.is_integer() and number >= 0: |
| 182 | + recursive_result = decimal_to_binary_recursive(int(number)) |
| 183 | + print(f"Recursive method (integer only): {recursive_result}") |
| 184 | + |
| 185 | + print("-" * 40) |
| 186 | + |
| 187 | + except (KeyboardInterrupt, EOFError): |
| 188 | + print("\n\nProgram terminated by user. Goodbye!") |
| 189 | + break |
| 190 | + except Exception as e: |
| 191 | + print(f"\nAn unexpected error occurred: {e}") |
| 192 | + print("Please try again with a different number.") |
| 193 | + print("-" * 40) |
| 194 | + |
| 195 | + except (KeyboardInterrupt, EOFError): |
| 196 | + print("\n\nProgram terminated. Goodbye!") |
| 197 | + |
| 198 | + |
| 199 | +def run_example() -> None: |
| 200 | + """ |
| 201 | + Run example conversions for demonstration purposes. |
| 202 | + Useful when running in non-interactive environments. |
| 203 | + """ |
| 204 | + print("=== Example Conversions (Non-interactive Mode) ===") |
| 205 | + examples = [10.0, 15.75, -3.125, 0.5, 255.255] |
| 206 | + |
| 207 | + for example in examples: |
| 208 | + binary_result = decimal_to_binary(example) |
| 209 | + print(f"Decimal: {example:8} -> Binary: {binary_result}") |
| 210 | + |
| 211 | + print("\nTo use interactive mode, run the program in a terminal.") |
56 | 212 |
|
57 | 213 |
|
58 |
| -# Driver Code |
59 | 214 | if __name__ == "__main__":
|
60 |
| - # decimal value |
61 |
| - dec_val = 24 |
62 |
| - |
63 |
| - # Calling function |
64 |
| - DecimalToBinary(dec_val) |
65 |
| -# master |
| 215 | + try: |
| 216 | + main() |
| 217 | + except (EOFError, KeyboardInterrupt): |
| 218 | + print("\n\nNo interactive input available. Running in example mode.") |
| 219 | + run_example() |
0 commit comments