python3 returns unsupported operand when bit shifting an element in a list?

Viewed 158

I have a list of hex values and I need to shift eacgh element by 9 and combine the result with another list. I have provided an example below of what I tried.

x = [hex(10), hex(11)]
y = x[0] << 1

This results in an error:

TypeError: unsupported operand type(s) for <<: 'str' and 'int'

While the below code works as I like but returns an int

x = [0xa, 0xb]
y = x[0] << 1

My question is how can I get the first code example to work?

I understand that the list is returning a string and not an int. I tried to type cast from a str to a hex, but this caused an error. I then tried to type cast from the string to int to hex and received an error for the str to int type cast.

I need to result to be stored as a hex in the list so changing the list to integers would not work for me.

2 Answers

The best way is to use the constructor 'int' with basis 16 to convert the hex values to integers, then use the bitwise operators

    a=hex(10)
    b=hex(11)
    x = [int(a,16),int(b,16)]
    y = x[0] << 1

    print(x)
    print(y)

You can convert hex strings to integers using

    int(hex(10), base=16)

but that would just return 10.

If you have a list of integers, I would first shift them the amount you need to shift them by, and then convert them to hexadecimal strings using hex. The value of a hex and its integers are the same, e.g. 0xa == 10 is True. But hex(10) returns a string.

So

    nums = [10, 11, ...]
    nums = [x << 9 for x in nums]
    hex_nums = map(hex, nums)

or something similar.

Related