I would like to represent a value as a 64bit signed long
, such that values larger than (2**63)-1 are represented as negative, however Python long
has infinite precision. Is there a 'quick' way for me to achieve this?
相关问题
- how to define constructor for Python's new Nam
- streaming md5sum of contents of a large remote tar
- How to get the background from multiple images by
- Evil ctypes hack in python
- Correctly parse PDF paragraphs with Python
Can you use numpy? It has an int64 type that does exactly what you want.
It's transparent to users, unlike the ctypes example, and it's coded in C so it'll be faster than rolling your own class in Python. Numpy may be bigger than the other solutions, but if you're doing numerical analysis, you will appreciate having it.
The quickest thing is probably to truncate the result to 64 bits yourself:
You can of course define your own numeric type that automatically does this every time you do any sort of arithmetic operation:
but that is not particularly "quick" to implement.
Have a look at the ctypes module, it is used to call foreign DLLs/libraries from python. There a some data types that correspond to C types, for example
You could use
ctypes.c_longlong
:This is really only an option if you know for sure that a
signed long long
will be 64 bits wide on the target machine(s).Edit: jorendorff's idea of defining a class for 64 bit numbers is appealing. Ideally you want to minimize the number of explicit class creations.
Using
c_longlong
, you could do something like this (note: Python 3.x only!):In this way the result of
ll(2 ** 63) - 1
will indeed be9223372036854775807
. This construction may result in a performance penalty though, so depending on what you want to do exactly, defining a class such as the above may not be worth it. When in doubt, usetimeit
.