Convert long series keys to hex, then Choose desired values from a list of long separated keys

Question:

I have code to generate series of keys as in below:

def Keygen (x,r,size):
 key=[]
 for i in range(size):
    x= r*x*(1-x) 
    key.append(int((x*pow(10,16))%256))
 return key   
if __name__=="__main__":
    key=Keygen(0.45,0.685,92)#Intial Parameters 
    print('nx key:', key, "n")  

The output keys are:

nx key: [0, 11, 53, 42, 111, 38, 55, 102, 252, 155, 54, 219, 149, 220, 235, 177, 140, 46, 209, 249, 46, 241, 218, 243, 6, 166, 247, 106, 33, 24, 220, 185, 129, 182, 214, 210, 180, 28, 84, 117, 228, 213, 205, 240, 125, 37, 181, 234, 246, 54, 22, 195, 38, 174, 212, 166, 9, 237, 25, 225, 81, 23, 244, 235, 171, 196, 111, 182, 227, 26, 22, 246, 35, 52, 225, 249, 90, 237, 162, 111, 76, 52, 35, 24, 16, 11, 7, 5, 3, 2, 1, 1]

I try to convert all key values to hex by used the following code:

K=hex(key)
print('nx key:', key, "n") 

But when run I got the error "TypeError: ‘list’ object cannot be interpreted as an integer" 

Then try to use "K= hex(ord(key))" but also got another error "TypeError: ord() expected string of length 1, but list found"

What I need is to convert all keys to hex, then select just 4 keys to be like this 

K = (0x3412, 0x7856, 0xBC9A, 0xF0DE)
Asked By: Mohammed Farttoos

||

Answers:

In order to get hex values for your list of keys, you have to iterate over the list and turn each element seperately into a hex value:

K = tuple(hex(x) for x in key)

Then you can select 4 random keys (no repeat) from this list by:

import random
selectedKeys = random.sample(K, 4)
Answered By: Lexpj

Maybe a better name for key is keys, cause is a list of keys. That said

[hex(key) for key in keys]

should do the trick.

This a is a usage of list comprehension

Answered By: Franco Milanese

Based on your output with your values wrapped in [], you have a list for key. What you then want to do is iterate through each element in that list to apply your hex.

hexed_keys = [hex(i) for i in key]
Answered By: John B.
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.