Question

I'm not sure whether this is a simple question or not, I am still relatively new to Python... but anyway I'll get right to it. As of right now I have a program which is converting every 2 hexadecimal numbers to decimal numbers (this will make more sense in the example.) They are each separated by a comma and can be of an indefinite length.... what I'm wondering is if there is a way to convert each number back to a hex number, concatenate those hex numbers, and then convert that number to a decimal... I do not want to mess around with the rest of the conversion because I did not write the first part and pieces of it are necessary for other operations of the program...

So to put this visually for everyone:

Here is the decimal I have as of now: (65, 222, 102, 102)

Here is the hex it came from: 41de6666 (so 41 base 16 = 65 base 10, de base 16 = 222 base 10 etc.)

And here is the decimal I would actually want to have: 1105094246

Thank you guys for any input you have on this it is much appreciated

Edit: and to clarify I do not have the 41de6666 available to me to easily just convert that to decimal, I need to convert the first given list to the end result

Was it helpful?

Solution

Here's a Python 3 version. It uses the struct.unpack method to build a big-endian 4-byte integer:

>>> import struct
>>> x=(65,222,102,102)
>>> struct.unpack('>L',bytes(x))[0]
1105094246

The Python 2 version doesn't have bytes, so use pack to build the byte string that will be unpacked:

>>> import struct
>>> x=(65,222,102,102)
>>> struct.unpack('>L',struct.pack('4B',*x))[0]
1105094246

The *x syntax expands the tuple into the four parameters expected by pack.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top