Last active
February 10, 2023 13:47
-
-
Save devmike01/f512f27196d2c4d4d0368a985830793a to your computer and use it in GitHub Desktop.
A simple script which converts decimal number to 8 bit binary code
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
To run: | |
- Download this code as .py | |
- Install python3 on your machine | |
- Open your CMD(Windows) or Terminal in Linux/MacOS and use the following command | |
python3 /Path/to/binary_to_decimal.py [COMMAND] [DECIMAL_NUMBER] | |
- COMMANDS | |
* -b : To convert decimal to binary | |
* -d : To convert binary to decimal | |
Milestone | |
- Convert decimal number to bits * | |
- Convert binary to decimal number * | |
- Handle signed bytes | |
Note: | |
This code will fail if the number is negative. | |
No bit flipping at the moment. | |
""" | |
import sys | |
def my_main(): | |
env_arg = sys.argv | |
if len(env_arg) < 3: | |
print("Run script in command and pass a valid decimal") | |
else: | |
try: | |
inp = int(env_arg[2]) | |
command = str(env_arg[1]) | |
if (command == "-d"): | |
# Convert from binary to decimal | |
print("Binary code: {}".format(binary_to_decimal(inp))) | |
elif (command == "-b") : | |
#Convert from decimal to binary | |
print("Result decimal : {}".format(covert_to_binary(inp))) | |
else: | |
print("Wrong command. You can either use -d or -b!") | |
except Exception as error: | |
print("An error has occurred! "+ str(error)) | |
def covert_to_binary(inp): | |
final_result = "" | |
tracker = inp | |
for i in range(8): | |
result = int(tracker % 2) | |
tracker = tracker/2 | |
final_result += str(result) | |
return final_result[::-1] | |
def binary_to_decimal(inp): | |
base = 1 | |
str_inp = str(inp)[::-1] | |
decimal =0 | |
for i in range(len(str_inp)): | |
res = base * int(str_inp[i]) | |
if res > 0: | |
decimal += res | |
base *= 2 | |
return decimal | |
if __name__ == "__main__": | |
my_main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment