将转换字符串的补码转换为二进制并显示字符串

时间:2019-11-07 10:56:14

标签: python python-3.x

我正在尝试实现一个代码,该代码可以接受字符串并将其转换为二进制,然后再补充二进制并将其再次转换为字符串。在我的代码中,我已经完成了将字符串转换为二进制的操作,而当我将该二进制代码输入一次补码时,出现的问题是 1的补码:000 2的补码:001 在下面的代码中将字符串转换为二进制

     def string2bits(s=''):
    return [bin(ord(x))[2:].zfill(8) for x in s]

def bits2string(b=None):
    return ''.join([chr(int(x, 2)) for x in b])

s = 'Hello'
b = string2bits(s)
s2 = bits2string(b)

print ('String:')
print (s)

print ('\nList of Bits:')
for x in b:
    print(x)

print ('\nString:')

假设您输入字符串:Hello;输出将 ['01001000','01100101','01101100','01101100','01101111']

之后,我尝试在下面的代码中进行一次补码,但向我显示结果: 1的补码:000 2的补码:001

一个人的补码

import string_binary as x
# Python3 program to print 1's and 2's 
# complement of a binary number 

# Returns '0' for '1' and '1' for '0' 
def flip(c): 
    return '1' if (c == '0') else '0'

# Print 1's and 2's complement of 
# binary number represented by "bin" 
def printOneAndTwosComplement(bin): 

    n = len(bin) 
    ones = "" 
    twos = "" 

    # for ones complement flip every bit 
    for i in range(n): 
        ones += flip(bin[i]) 

    # for two's complement go from right 
    # to left in ones complement and if 
    # we get 1 make, we make them 0 and 
    # keep going left when we get first 
    # 0, make that 1 and go out of loop 
    ones = list(ones.strip("")) 
    twos = list(ones) 
    for i in range(n - 1, -1, -1): 

        if (ones[i] == '1'): 
            twos[i] = '0'
        else:        
            twos[i] = '1'
            break

    # If No break : all are 1 as in 111 or 11111 
    # in such case, add extra 1 at beginning 
    if (i == -1): 
        twos.insert(0, '1') 

    print("1's complement: ", *ones, sep = "") 
    print("2's complement: ", *twos, sep = "") 

# Driver Code 
if __name__ == '__main__': 
    bin = "x.b"
    printOneAndTwosComplement(bin.strip("")) 

,在最后的代码中,我试图显示字符串 但是它给定的问题第17行,在print(chr(int(x [8:],2)))

OverflowError:Python int太大,无法转换为C long

将二进制转换为字符串代码:

import sys 
x = "10001111100101110010111010111110011110011011011111110010100011111001011100101110101111100111"
print(chr(int(x[:8], 2)))
print(chr(int(x[8:], 2)))

0 个答案:

没有答案