基本上,对于这个实践问题,我必须将ASCII字符串输入转换为二进制,然后将其转换为一元,一系列0和空格。
例如:'C'='1000011'='0 0 00 0000 0 00'。
不幸的是,代码只在打印变量'answer'时打印一个空行,该变量应该是0和空格字符串。我找不到任何错误,但两个编译器返回相同的空行。
import sys
import math
import binascii
# Auto-generated code below aims at helping you parse
# the standard input according to the problem statement.
message = "C"#input()
# Function which transforms text into a byte
def text_to_bits(text, encoding='utf-8', errors='surrogatepass'):
bits = bin(int(binascii.hexlify(text.encode(encoding, errors)), 16))[2:]
return bits.zfill(8 * ((len(bits) + 7) // 8))
# Sets up a switch to determine which block and of what type it is in
switch = 2
answer = ""
# Transforms string message into string of bits
byte = text_to_bits(message)
byte = byte[1:8]
for bit in byte:
if bit == 1 and switch == 2:
switch = 1
answer = answer + "0 0"
elif bit == 1 and switch == 1:
answer = answer + "0"
elif bit == 1 and switch == 0:
switch = 1
answer = answer + " 0 0"
elif bit == 0 and switch == 2:
switch = 0
answer = answer + "00 0"
elif bit == 0 and switch == 1:
switch = 0
answer = answer + " 00 0"
elif bit == 0 and switch == 0:
answer = answer + "0"
# Write an action using print
# To debug: print("Debug messages...", file=sys.stderr)
print(answer)
答案 0 :(得分:0)
bit
的值始终为'0'
或'1'
。它永远不会等于0
或1
,因此级联if
中的所有条件都不是真的。将0
和1
更改为相应的字符串。
答案 1 :(得分:0)
您的比较运算符不正确,您需要执行以下操作:
if bit == "1" and switch == 2:
...