2014-04-25 86 views
0

從我可以告訴,隨機函數返回位。那麼爲什麼類型(鍵)給我「串」?如果它是一個字符串,或如果它的位,我怎麼不能打印出來?如果我打印出來,它會給出計算機無法讀取的無意義字符。可以Python打印位

def random(size=16): 
    return open("/dev/urandom").read(size) 

key = random() 
print type(key) 

回答

3

在Python中,一串字節(或位)表示爲一個字符串。打印出的無意義字符是因爲並非所有位組合都映射到ASCII編碼中的有效字符:http://en.wikipedia.org/wiki/ASCII

如果要將隨機位看作1s和0s,則可以將每個位字符使用ord,然後一個數字格式化數字爲二進制:

s = random() 
print "".join(map("{0:08b}".format, map(ord, list(s)))) # 8 bits per byte 

如果你想生成隨機數,爲什麼不使用random module呢?

0

這是蟒蛇如何與比特和字符串:)

代碼工作

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)