二进制计算的一般做法是:
1.将二进制串按照8位一组分开;
2.将8位一组的二进制串计算成十进制数(十六进制也可以);
3.对照二进制编码表,将十进制数转换成字符串。
例如将以下二进制串变换成字符串:
011000010100100001010010001100000110001101000100011011110111011001001100001100110110010000110011011001000111100100110101011110100110000101000111011011000011010101011001010101110011010101101001010110010101100001001001011101010101100100110010001110010111010001001100001100100100111000110000010110100110100100111000011110000100111101000100010010010011000001010010011011010111100001101000010110100011000001101100011110100101100101010110010101100101001101010100010000010011110100111101
将二进制串8位一组分开的话,有很多种方法:
1. 用for循环,8位一组分开:
s = "011000010100100001010010001100000110001101000100011011110111011001001100001100110110010000110011011001000111100100110101011110100110000101000111011011000011010101011001010101110011010101101001010110010101100001001001011101010101100100110010001110010111010001001100001100100100111000110000010110100110100100111000011110000100111101000100010010010011000001010010011011010111100001101000010110100011000001101100011110100101100101010110010101100101001101010100010000010011110100111101"
最后的输出结果为:
aHR0cDovL3d3dy5zaGl5YW5iYXIuY29tL2N0Zi8xODI0RmxhZ0lzYVVSTA==
BASE64直接解码:
import base64
base64.decode('aHR0cDovL3d3dy5zaGl5YW5iYXIuY29tL2N0Zi8xODI0RmxhZ0lzYVVSTA==')
2.采用re模块的findall
''.join([chr(int(x,2)) for x in re.findall(".{8}",s)])
不加''.join是输出的是列表,通过''.join将列表的内容组合成字符串。
第二种方式最为简单,但需要对迭代和正则表达式比较熟悉。