Anthony
Anthony

Reputation: 1876

Integer to list

I'm trying to convert a number into a list of ints (preferably hex, but I know that's in my control via print formatting):

0xFFFF

should turn into:

[0xFF, 0xFF]

I will admit I am very confused about Python's ability to handle lower level information like bytes. I have been reading about bytes, bytearray, and similar methods for hours without being able to succeed at this task in a way that seems efficient. I am trying to understand how to do it in the most Pythonic and efficient way.

This is what I've come up with so far for string inputs:

>>> [ord(x) for x in '0xFFFF'.replace('0x','').decode('hex')]
[255, 255]

And int inputs:

>>> v = 0xFFFF
>>> [ord(x) for x in '{:04x}'.format(v).decode('hex')]
[255, 255]

I know the list can be formatted like this:

>>> a = list(ord(x) for x in '0xFFFF'.replace('0x','').decode('hex'))
>>>'[{}]'.format(', '.join([hex(x).upper() for x in a]))
'[0XFF, 0XFF]'

Is there a cleaner way to do the conversions and then output formatting? None of the questions or answers I've found on Stack Overflow or Google have matched this particular situation, but maybe I just missed something. Any help would be greatly appreciated.

Edit: I apologize - my original question did not exactly represent what I was trying to accomplish. In my quest to make a minimum reproducible example, I skipped something important: 0xFFFF should be able to be a number or a string. It's fine to do it in separate operations/functions.

Upvotes: 3

Views: 183

Answers (2)

Swetank Subham
Swetank Subham

Reputation: 169

If you want to separate it by making group of some specific numbers of character then you can do it simply using textwrap's wrap function. In our case the number of characters in group is 2.

>>>from textwrap import wrap
>>>v = 0xFFFF
>>>print list('0x' + x.upper() for x in wrap(str(hex(v))[2:], 2))
>>>v = 0xFFFFF
>>>print list('0x' + x.upper() for x in wrap(str(hex(v))[2:], 2))
>>>print list(int('0x' + x, 16) for x in wrap(str(hex(v))[2:], 2))

Output:

>>>['0xFF', '0xFF']
>>>['0xFF', '0xFF', '0xF']
>>>[255, 255, 15]

*Note: wrap function makes the group from starting of the string and if the length of string is not the multiple of the number of which we have to make groups, it will make group of remaining characters (as making groups from starting of the string) at last.

Upvotes: 3

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476564

The formatting can be handled with the default string formatting in Python:

'[{}]'.format(', '.join(map('0x{:02X}'.format, a)))

'{:02x}' means that we print the number as a hexadecimal one (x), with at two leading zeros (02) if necessary.

As for the conversion from a string to a list of integers, the following is probably more elegant:

list(bytes.fromhex('0xFFFF'.replace('0x', '')))

for example:

>>> list(bytes.fromhex('0xFFFF'.replace('0x', '')))
[255, 255]

Upvotes: 2

Related Questions