-1

So, I have a list containing strings that represent hex values like:

['02', 'ff', '98', '80', '39', '31', '03']

I would like to generate a new list that contains the actual hex values like:

[0x02, 0xff, 0x98, 0x80, 0x39, 0x31, 0x03]

Is there a way to do that?

If needed I can also get acces to the actual byte stream in the form of:

b'\x02\xff\x9c\x80D1\x03'

I need this "transformation" to perform bit-a-bit boolean operations on the elements of the list

NicoCaldo
  • 1,171
  • 13
  • 25
  • 3
    What do you mean by 'actual hex values'? Hexadecimal is just a representation of an integer. – DarkKnight May 11 '22 at 08:53
  • @LancelotduLac "actual hex" meaning a rapresentation of a byte into hex format as I will need to apply boolean operations to them. Maybe I explained myself not in the best way – NicoCaldo May 11 '22 at 09:02
  • @KellyBundy I'm not sure what you mean. – juanpa.arrivillaga May 11 '22 at 09:02
  • 1
    The values in your list and your "actual byte stream" don't seem to match. What's up with that? – Kelly Bundy May 11 '22 at 09:03
  • 1
    @NicoCaldo the best way to be unambigous is to speak in terms of the *type of object you want*. Your question implies you want the `int` objects with the corresponding hexadecimal values – juanpa.arrivillaga May 11 '22 at 09:03
  • @KellyBundy the OP says they want a `bytes` objects. Presumably to pass to something that expects a `bytes` object. If they want to work with a sequence of integer values, then yeah, just using `vals = [int(x, 16) for x in data]` would be better – juanpa.arrivillaga May 11 '22 at 09:05
  • @KellyBundy ah, you are right, i misread the last part. Yes, presumabbly the OP should just do `list(bytestream)` to get to the list of integers, not do an intermediate conversion to strings – juanpa.arrivillaga May 11 '22 at 09:07

1 Answers1

3

You can convert the hexadecimal string representations like this:

a = ['02', 'ff', '98', '80', '39', '31', '03']

b = [int(x, 16) for x in a]

This will create a list with integer equivalents of the input strings

DarkKnight
  • 19,739
  • 3
  • 6
  • 22