-1

Let's say I have two given hex values which are str as datatype:

a = 0x15
b = 0x18

Now I would like to append them so that I have as result:

0x1518

The normal way would be to cast the values to int to be able to append, like:

(hex( (int(a)<<8) | int(b) ))

I'm getting the error:

ValueError:invalid literal for int() with base 10: '0x15'

What I'm doing wrong here?

JohnDoe
  • 825
  • 1
  • 13
  • 31

4 Answers4

2

You need to tell int that the numbers are in base 16:

hex((int(a, 16) << 8) | int(b, 16))
ash
  • 5,139
  • 2
  • 27
  • 39
1

a and b are int values already you don't have to cast them

hex_value = hex(a << 8 | b)

if it still doesn't work you can use the string format to convert the int into hex

hex_value = '0x{:04x}'.format(a << 8 | b)
Du D.
  • 5,062
  • 2
  • 29
  • 34
0

The code you're running is not the code you posted. (what you posted, works fine).

Your 'a' is not what you think it is. You're trying to feed the string "0x15" to the int() function, and it rightfully complains to you that this isn't an integer in base 10 notation.

Fix your variable types and get rid of the int() calls.

Irmen de Jong
  • 2,739
  • 1
  • 14
  • 26
0

The code you posted works fine. I don't know where you are getting the error from.

On a side note, a and b are not strings; they are already of type int so there is no need to type-cast. You can verify this:

>>> a = 0x15
>>> type(a)
<class 'int'>

Removing unnecessary type-casting you get (hex(a << 8 | b )), which will give you the correct result.

A.B.
  • 169
  • 10
  • when I type type(a) I get "str". This value is received from an other module in str datatype. For further use I needed to convert it to string. – JohnDoe Jan 26 '18 at 15:36