If I have two hex-strings and want to convert one to an 32-bit unsigned integer and the other to a 64-bit unsigned integer, what bases would I provide the int()
function?

- 1,543
- 6
- 28
- 61
-
See [this question](http://stackoverflow.com/questions/7675222/in-javascript-how-is-integer-represented-in-storage-layout) – Akshat Mahajan Aug 02 '16 at 17:31
-
Take a look at this http://stackoverflow.com/questions/2104884/how-does-python-manage-int-and-long – Yotam Salmon Aug 02 '16 at 17:34
2 Answers
Well, python usually decides how much memory to allocate itself. See the following example:
>>> type(int('0x7fffffff', 16))
<type 'int'>
>>> type(int('0x80000000', 16))
<type 'long'>
Based on the size of the number, Python allocates the right amount of memory.
BUT if you use the method long()
instead of int()
, always 8 bytes will be allocated, no matter what the number is:
>>> type(long('0x7fffffff', 16))
<type 'long'>
>>> type(long('0x80000000', 16))
<type 'long'>
*Tested for Python 2.7 (not tested with 3.x)

- 2,400
- 22
- 36
-
In python 3 there is no difference between int and long. Each integer number can be arbitrarily big (as long as you have sufficient memory). – warownia1 Aug 08 '16 at 16:48
So I goofed up and int() does not determine the size or sign of your hex string.
By definition, hex is 16. So you would put in your string with the hex base of 16
int('A1S31231', 16)
The issue between 32 bit and 64 bit was simply the size of the string put in as an argument.
By virtue of their size,
2 hex characters = 1 byte
So if I had a 64 bit int, it would be 8 bytes or a 16 character hex string. If I had a 32 bit int, it would be 4 bytes or 8 character hex string.
Based off Duncan's answer: In order to make your result unsigned. You would need to take your result and &
them with their proper mask.
If you're looking to go from hex to an uint32 you would do the aforementioned int() conversion and then
result & 0xffffffff
If you wanted to go from hex to uint64 you would do the aforementioned int() conversion and then
result & 0xffffffffffffffff