简体   繁体   English

如何在python中创建一个六进制随机数?

[英]How to create an hexa randomly numbers in python?

I want to create a file of hexadecimal number where everyone is composed of 32 elements like this: 我想创建一个十六进制文件,每个人都由32个元素组成,如下所示:

ccddeeff8899aabb4455667fffffff33
e0370734313198a2885a308aaaaaaaa8
7354776f204f6e65204e696bbbbbbb6f
64976fbb4f6e6ee0cc681e6ccccccc77

I try by this code to create my numbers but I don't now how to have 32 elements for each number: 我尝试通过此代码创建数字,但是现在我不知道如何为每个数字包含32个元素:

   import random
   Plaintext_file = open("C:\\Users\\user\\Plaintexts.txt", "w")
   for i in range(5):
      i = random.randint(0, 16777215)
      print "%x" % i 
      Plaintext_file.write("%x \n" % i)

The result that I have: 我得到的结果是:

c39ea9
a737a0
d2d352
fcebf1
ade761

I would be very grateful if you could help. 如果您能提供帮助,我将不胜感激。

Use binascii.b2a_hex to convert binary data to a line of ASCII characters, 使用binascii.b2a_hex将二进制数据转换为一行ASCII字符,

>>> import os,binascii
>>> binascii.b2a_hex(os.urandom(16))
'a8922d48fba3bddd0214a338ce090ea6'

os.urandom(n) returns a string of n random bytes from an OS-specific randomness source. os.urandom(n)从特定于操作系统的随机性源返回n随机字节的字符串。

>>> import uuid
>>> uuid.uuid4().hex
'd734fde6d45e47e99d06f129b5c128f8'

You can use random.choice using the list of accepted hex chars (from string.hexdigits ): 您可以使用可接受的十六​​进制字符列表(来自string.hexdigits )使用random.choice

>>> import string
>>> string.hexdigits
'0123456789abcdefABCDEF'
>>> import random
>>> "".join([random.choice(string.hexdigits) for x in range(32)])
'37bAA921dd6BE09eEff45c280D62FFAb'

If you want only the lowercase you case use string.hexdigits[:16] : 如果只需要小写字母,请使用string.hexdigits[:16]

>>> import string
>>> string.hexdigits[:16]
'0123456789abcdef'
>>> import random
>>> "".join([random.choice(string.hexdigits[:16]) for x in range(32)])
'805cb6c9b38515b588bfec42613eff9d'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM