'read a file and converts each decimal into a binary number
Reads the text file (the file name is given as a parameter) and converts each decimal number into a binary number. All decimal numbers are positive, so you do not need to account for the negative scenario. Print each converted binary number to the console, one per line. (Create a module named binary that has each of the functions listed below. You will notice these functions are used in the main.py file, which is how you will test your code).
File dec2bin.txt
11
2090
103
58
9049
20012948
129129
291
2039193
1234872589
8717950

main.py
import binary as b
b.dec2bin("dec2bin.txt")
print()
what am I doing wrong? my code is not working and I tried different coding.
Solution 1:[1]
def dec2bin(file):
with open(file, 'r') as f:
for line in f:
print(bin(int(line)).replace("0b", ""))
def bin2dec(file):
with open(file, 'r') as f:
for line in f:
print(int(line, 2))
Solution 2:[2]
# Inside binary.py file
def dec2bin(data):
lst = []
for a in data:
lst.append(bin(int(a))[2:])
return(lst)
# another file.
from binary import *
with open('test.txt') as f:
data = f.read().splitlines()
if __name__ == '__main__':
print(dec2bin(data))
OUTPUT
['1011', '100000101010', '1100111', '111010', '10001101011001', '1001100010101111110010100', '11111100001101001', '100100011', '111110001110110011001', '1001001100110101010100100001101', '100001010000011001111110']
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Sharim Iqbal |
| Solution 2 | Sharim Iqbal |
