Reputation: 39
I have an integer list arr with five elements/indexes ranging from arr[0] to arr[4]
The last three elements are customer number which ranges from 01 to 250,000. What I need is to convert them to hex in such a way that the array should look like:
For customer 1,
arr = [00,00,01,00,00]
- cust num is the last three bytes
For customer 2,
arr = [00,00,02,00,00]
- cust num is the last three bytes
For customer 250,000,
arr = [00,00,90,d0,03]
- cust num is the last three bytes, 250,000 in hex = 3D090
I know I can use hex() function to individually convert the indexes to hex or can convert the whole array to hex, but how do I convert the value to hex and place it in last three bytes as in the above format?
Upvotes: 1
Views: 171
Reputation: 19885
This will work:
i = 250000
constant = ['00', '00']
result = [constant + [first + second
for first, second in zip(string[::2], string[1::2])][::-1]
for string in (f'{i:X}'.zfill(6) for i in range(1, 250001))]
print(result[0])
print(result[-1])
For Python <= 3.5:
i = 250000
constant = ['00', '00']
result = [constant + [first + second
for first, second in zip(string[::2], string[1::2])][::-1]
for string in ('{:X}'.format(i).zfill(6) for i in range(1, 250001))]
print(result[0])
print(result[-1])
Output:
['00', '00', '01', '00', '00']
['00', '00', '90', 'D0', '03']
Explanation:
First, we recognise that we can use string formatting to convert each number into a string, which is then padded to length 6 with 0
if needed.
Next, we chunk the string into two-character blocks and reverse it so that it has the representation required.
Lastly, we add two '00'
strings to each inner list
.
Upvotes: 1
Reputation: 139
Might help
import re
def split_hex_rev(number):
arr = re.findall('..',hex(number).replace('x',''))
while len(arr)<5:
arr.append('00')
arr.reverse()
return arr
Upvotes: 0