Python Forum
How to create random hex message
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to create random hex message
#1
Hello
need your help in a simple issue:

I want to create a random 16 chars message from this (0123456789ABCDEF)
so the output will be like this:
"AAB1C70ADD84C701"

I mange only to create a random int
 new_data = random.randint(111111111111,999999999999)
but how do I add Hex values?

Thanks ,
Reply
#2
(Jan-25-2021, 03:18 PM)korenron Wrote: Hello
need your help in a simple issue:

I want to create a random 16 chars string from this (0123456789ABCDEF)
so the output will be like this:
"AAB1C70ADD84C701"

I mange only to create a random int
 new_data = random.randint(111111111111,999999999999)
but how do I add Hex values?

Thanks ,
Reply
#3
Here's one option:

from random import randint
chars = '0123456789ABCDEF'
hex_array = [chars [randint (0, 15)] for x in range (16)]
hex_string = ''.join (hex_array)
print (hex_string)
Reply
#4
>>> import random
>>> f"{random.randint(0,2**(4*16)):016X}"
'47A30C8F1A3627C7'
Picks a random number between 0 and 0xFFFFFFFFFFFFFFFF, then prints that number out as as 16 digit hex string.
Reply
#5
You could also use the uuid module, since uuids are random and hex strings.

import uuid

rand_id = uuid.uuid4()
as_hex = rand_id.hex
value = as_hex[:16]
print(value)
#=> 00fcabb895d144d3
But the best is probably to be explicit about what you're doing...
import random
import string

# 0-9, a-f, A-F
chars = string.hexdigits
# remove a-f
chars = list(set(chars.upper()))
message = ''.join(random.choice(chars) for _ in range(16))
print(message)
#=> 671A097FE9A211FB
Reply
#6
Similar to bowlofred solution:
import random


def get_random_hex_str(hex_length):
    if hex_length % 2 != 0:
        raise ValueError("hex_length must be even")
    maximum = 2 ** (4 * hex_length) - 1
    value = random.randint(0, maximum)
    return f"{value:0{hex_length}x}"
A cryptographic safe solution is the use of os.urandom

import os
from binascii import hexlify


def get_random_hex_str(hex_length):
    if hex_length % 2 != 0:
        raise ValueError("hex_length must be even")
    return hexlify(os.urandom(hex_length // 2)).decode()
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply
#7
Thank you all for the help !

so many options to choose from Smile

Thanks ,
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  [split] why can't i create a list of numbers (ints) with random.randrange() astral_travel 7 1,531 Oct-23-2022, 11:13 PM
Last Post: Pedroski55
  how to create my own custom logging message maiya 4 2,365 Jul-15-2020, 05:42 PM
Last Post: maiya
  Create random pairs Dennisp44 3 8,020 Jun-02-2018, 05:51 AM
Last Post: buran

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020