0

I want to create a file of hexadecimal number where everyone is composed of 32 elements like this:

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:

   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.

6
  • 2
    where does 16777215 come from? It's not 16**32. Commented Dec 7, 2016 at 14:35
  • i = random.randint(0, 16**32) Doesn't give me 32 elements, sometimes it gives me 31 elements Commented Dec 7, 2016 at 14:38
  • 3
    because the first digit is zero 1/16 of the time. (use "%032x" to force width to be 32 with zero padding). Commented Dec 7, 2016 at 14:40
  • No I am sorry It doesn't work Commented Dec 7, 2016 at 14:46
  • I still have the same problem Commented Dec 7, 2016 at 14:50

3 Answers 3

2

Use binascii.b2a_hex to convert binary data to a line of ASCII characters,

>>> 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.

Sign up to request clarification or add additional context in comments.

Comments

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

2 Comments

It works but I need to return back to line, Plaintext_file.write("\n" % i)this one doesn't work
Plaintext_file.write("%s\n" % uuid.uuid4().hex)
1

You can use random.choice using the list of accepted hex chars (from string.hexdigits ):

>>> 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]:

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

2 Comments

@nani92, did you check this code? I'm not so sure what/where exactly is the problem.
Using '0123456789abcdefABCDEF' increases the chances of picking a hex digit in the range a..f. It might be better to use '01234567890123456789abcdefABCDEF' if case is significant in the result.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.