因此,我有这个程序,可以给出ascii值的二进制值加上用户输入字符串的1。
text = input()
bitString = ''
for ch in text:
new = ord(ch) + 1
decimal = new
while decimal > 0:
remainder = decimal % 2
decimal = decimal // 2
bitString = str(remainder) + bitString
print(bitString)
如果用户输入“ abcde”,则输出为
11001101100101110010011000111100010
如何获得二进制值,用空格分隔,输出将在哪里
1100010 1100011 1100100 1100101 1100110
?
尝试像这样最后使用空格
remainder = decimal % 2
decimal = decimal // 2
bitString = str(remainder) + bitString + " "
这应该解决
在您的代码中稍作更改以增加空间:
text = input()
bitString = ''
for ch in text:
new = ord(ch) + 1
decimal = new
while decimal > 0:
remainder = decimal % 2
decimal = decimal // 2
bitString = str(remainder) + bitString
bitString = " " + bitString
print(bitString)
输出:
1100010 1100011 1100100 1100101 1100110
尝试一下:
revBitString = bitString[::-1]
print(' '.join([revBitString[i:i+7][::-1] for i in range(0,len(revBitString),7)]))
这里是解决方法:
text = input()
bitString = ''
for ch in text:
new = ord(ch) + 1
decimal = new
while decimal > 0:
remainder = decimal % 2
decimal = decimal // 2
bitString = str(remainder) + bitString
splitStr = [bitString[i:i+7] for i in range(0, len(bitString), 7)]
print(" ".join(splitStr[::-1]))
结果:
1100010 1100011 1100100 1100101 1100110
OR
text = input()
bitString = ''
for ch in text:
new = ord(ch) + 1
decimal = new
while decimal > 0:
remainder = decimal % 2
decimal = decimal // 2
bitString = str(remainder) + bitString
bitString = " " + bitString
print(" ".join(bitString.split()[::-1]))
结果:
1100010 1100011 1100100 1100101 1100110
input = 'abcde'
bitString = ''
for i in list(input):
bitString = bitString + bin(ord(i)+1)[2:] + ' '
print(bitString)
我希望你想这样。