I am using the latest version of python and my IDE is the latest version of pycharm. I am attempting to convert RLE or raw data to hexadecimal. An example of the raw input would be [3, 15, 6, 4]. I don't know how I would go about removing the commas and brackets so that I could convert the raw data to hexadecimal or if I even have to remove the commas and brackets to convert. Any help would be appreciated.
For the example I provided input: [3, 15, 6, 4] output: 3f64
CodePudding user response:
If the brackets are part of your string, you could make list of hexadecimal numbers by using
nums = [hex(element) for element in str[1:-1].split(',')]
CodePudding user response:
string = "[3, 15, 6, 4]"
list_of_numbers = string[1:-1].split(", ") # gives us list_of_numbers = ['3', '15', '6', '4']
output = ""
for number in list_of_numbers:
output = output hex(int(number))[2:] # we need to convert our number to an int and then to hex
output should be 3f64, you get rid of the brackets by selecting a substring with [1:-1] and then you get rid of the commas/spaces with the split command
CodePudding user response:
In case the input is an array of int values:
a = [3, 15, 6, 4]
b = ""
for v in a:
b = f'{b}{v:x}'
print(f'0x{b}')
In case the input is a string containing also brackets and commas:
import re
s = "[3, 15, 6, 4]"
# remove brackets and spaces, or other characters if required
replaced = re.sub('[\[\] ]', '', s)
# split by comma
a = replaced.split(',')
b = ""
for v in a:
b = f'{b}{int(v):x}'
print(f'0x{b}')
With string input using numpy:
import numpy as np
s = '[3, 15, 6, 4]'
# convert string to array of int values
a = np.fromstring(s[1:-1], dtype=int, sep=',')
# use built-in formatting option
b = np.array2string(
a,
separator='',
formatter={'int': lambda x: f'{x:x}'}
)[1:-1]
print(f'0x{b}')