我期待的结果是
>>> message_to bits('')
''
>>> message_to_bits('hello')
'0110100001100101011011000110110001101111'
但是我得到的是空字符串和字符串的错误,只有第一个字符的1和0:
def char_to_bits(char):
"""char_to_bits(char) -> string
Convert the input ASCII character to an 8 bit string of 1s and 0s.
>>> char_to_bits('A')
'01000001'
"""
result = ''
char_num = ord(char)
for index in range(8):
result = get_bit(char_num, index) + result
return result
def get_bit(int, position):
"""get_bit(int, position) -> bit
Return the bit (as a character, '1' or '0') from a given position
in a given integer (interpreted in base 2).
The least significant bit is at position 0. The second-least significant
bit is at position 1, and so forth.
>>> for pos in range(8):
... print(b.get_bit(167, pos))
...
1
1
1
0
0
1
0
1
"""
if int & (1 << position):
return '1'
else:
return '0'
def message_to_bits(message):
for char in message:
result="".join(str(bits.char_to_bits(char)))
return result
答案 0 :(得分:0)
你想加入两次:
def message_to_bits(message):
return "".join("".join(str(bits.char_to_bits(char))) for char in message)
第一个连接用于char中的位,第二个连接用于消息中的字符。