Python能打印比特吗
根据我的理解,随机函数返回的是一些比特(也就是计算机用来表示数据的基本单位)。那么,为什么当我查看类型时,得到的却是“字符串”呢?如果它是字符串,或者说是比特,为什么我不能把它打印出来?一打印出来就显示一些电脑看不懂的奇怪字符。
def random(size=16):
return open("/dev/urandom").read(size)
key = random()
print type(key)
2 个回答
0
下面是Python是如何处理位和字符串的 :)
代码
def __String_to_BitList(data):
"""Turn the string data, into a list of bits (1, 0)'s"""
if _pythonMajorVersion < 3:
# Turn the strings into integers. Python 3 uses a bytes
# class, which already has this behaviour.
data = [ord(c) for c in data]
l = len(data) * 8
result = [0] * l
pos = 0
for ch in data:
i = 7
while i >= 0:
if ch & (1 << i) != 0:
result[pos] = 1
else:
result[pos] = 0
pos += 1
i -= 1
return result
def __BitList_to_String(data):
"""Turn the list of bits -> data, into a string"""
result = []
pos = 0
c = 0
while pos < len(data):
c += data[pos] << (7 - (pos % 8))
if (pos % 8) == 7:
result.append(c)
c = 0
pos += 1
if _pythonMajorVersion < 3:
return ''.join([ chr(c) for c in result ])
else:
return bytes(result)
3
在Python中,一串字节(或者说比特)被表示为字符串。打印出来的那些奇怪字符,其实是因为并不是所有的比特组合都能对应到ASCII编码中的有效字符上:http://en.wikipedia.org/wiki/ASCII
如果你想把这些随机的比特显示成1和0,可以用ord
把每个字符转换成数字,然后把这个数字格式化成二进制:
s = random()
print "".join(map("{0:08b}".format, map(ord, list(s)))) # 8 bits per byte
如果你想生成随机数,为什么不直接使用random模块呢?