# 将二进制转换为ASCII，反之亦然

``bin(reduce(lambda x, y: 256*x+y, (ord(c) for c in 'hello'), 0))` `

` `0b110100001100101011011000110110001101111` `

` `>>> import binascii >>> bin(int(binascii.hexlify('hello'), 16)) '0b110100001100101011011000110110001101111'` `

` `>>> n = int('0b110100001100101011011000110110001101111', 2) >>> binascii.unhexlify('%x' % n) 'hello'` `

` `>>> bin(int.from_bytes('hello'.encode(), 'big')) '0b110100001100101011011000110110001101111'` `

` `>>> n = int('0b110100001100101011011000110110001101111', 2) >>> n.to_bytes((n.bit_length() + 7) // 8, 'big').decode() 'hello'` `

### 要在Python 3中支持所有的Unicode字符：

` `def text_to_bits(text, encoding='utf-8', errors='surrogatepass'): bits = bin(int.from_bytes(text.encode(encoding, errors), 'big'))[2:] return bits.zfill(8 * ((len(bits) + 7) // 8)) def text_from_bits(bits, encoding='utf-8', errors='surrogatepass'): n = int(bits, 2) return n.to_bytes((n.bit_length() + 7) // 8, 'big').decode(encoding, errors) or '\0'` `

### 这里是单源Python 2/3兼容版本：

` `import binascii 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)) def text_from_bits(bits, encoding='utf-8', errors='surrogatepass'): n = int(bits, 2) return int2bytes(n).decode(encoding, errors) def int2bytes(i): hex_string = '%x' % i n = len(hex_string) return binascii.unhexlify(hex_string.zfill(n + (n & 1)))` `

### 例

` `>>> text_to_bits('hello') '0110100001100101011011000110110001101111' >>> text_from_bits('110100001100101011011000110110001101111') == u'hello' True` `

` `bitstring = bitstring[2:] bitstring = -len(bitstring) % 8 * '0' + bitstring` `

` `string_blocks = (bitstring[i:i+8] for i in range(0, len(bitstring), 8)) string = ''.join(chr(int(char, 2)) for char in string_blocks)` `

# 内置的只有`python`

` `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, World!' b = string2bits(s) s2 = bits2string(b) print 'String:' print s print '\nList of Bits:' for x in b: print x print '\nString:' print s2` `

` `String: Hello, World! List of Bits: 01001000 01100101 01101100 01101100 01101111 00101100 00100000 01010111 01101111 01110010 01101100 01100100 00100001 String: Hello, World!` `

` `str = "0b110100001100101011011000110110001101111" str = "0" + str[2:] message = "" while str != "": i = chr(int(str[:8], 2)) message = message + i str = str[8:] print message` `

（注意：不是Python的人，但这似乎是一个明显的答案）

` `with open("Test1.txt", "r") as File1: St = (' '.join(format(ord(x), 'b') for x in File1.read())) StrList = St.split(" ")` `

` `StrOrgList = StrOrgMsg.split(" ") for StrValue in StrOrgList: if(StrValue != ""): StrMsg += chr(int(str(C.DecryptMsg(StrValue)),2)) print(StrMsg)` `

` `import binascii, sys def goodbye(): sys.exit("\n"+"*"*43+"\n\nGood Bye! Come use again!\n\n"+"*"*43+"") while __name__=='__main__': print "[A]scii to Binary, [B]inary to Ascii, or [E]xit:" var1=raw_input('>>> ') if var1=='a': string=raw_input('String to convert:\n>>> ') convert=bin(int(binascii.hexlify(string), 16)) i=2 truebin=[] while i!=len(convert): truebin.append(convert[i]) i=i+1 convert=''.join(truebin) print '\n'+'*'*84+'\n\n'+convert+'\n\n'+'*'*84+'\n' if var1=='b': binary=raw_input('Binary to convert:\n>>> ') n = int(binary, 2) done=binascii.unhexlify('%x' % n) print '\n'+'*'*84+'\n\n'+done+'\n\n'+'*'*84+'\n' if var1=='e': aus=raw_input('Are you sure? (y/n)\n>>> ') if aus=='y': goodbye()` `