你应该发布你自己的代码,而不是让别人为你写代码,你对我很刻薄。但这听起来对其他人来说是一个有用的问题,所以你去吧:
(迟到一周,以防万一这是作业)
# helper function with some basic math
def number(digits, base):
value = 0
for digit in digits:
value *= base
value += int(digit)
return value
if 826 != number('826', 10):
raise ValueError
if 64+16+2+1 != number([0, 1, 0, 1, 0, 0, 1, 1], 2):
raise ValueError
# helper function to break the data up into the expected chunks
# https://stackoverflow.com/a/312464/1766544
def chunks(arbitrary_list, chunk_size):
for i in range(0, len(arbitrary_list), chunk_size):
yield arbitrary_list[i:i + chunk_size]
data = [
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 1,
0, 0, 0, 0, 0, 0, 1, 0,
0, 0, 0, 0, 0, 1, 0, 0,
0, 0, 0, 0, 1, 0, 0, 0,
0, 0, 0, 1, 0, 0, 0, 0,
0, 0, 1, 0, 0, 0, 0, 0,
0, 1, 0, 0, 0, 0, 0, 0,
1, 0, 0, 0, 0, 0, 0, 0,
]
# the bytearray constructor needs an iterable
# the iterable needs to yield the number
# the number needs 8 bits at a time
binary_data = bytearray((number(bits, base=2) for bits in chunks(data, 8)))
# write the bytearray to a file is too easy
# there's already a function that writes stuff to a file
#with open ('filename.data', 'wb') as f:
#f.write(binary_data)
# but easier to demonstrate that we have the right values like so:
for n in binary_data:
print(n)
输出:
0
1
2
4
8
16
32
64
128