简体   繁体   中英

How to determine whether the number is 32-bit or 64-bit integer in Python?

I want to differentiate between 32-bit and 64-bit integers in Python. In C it's very easy as we can declare variables using int_64 and int_32 . But in Python how do we differentiate between 32-bit integers and 64-bit integers?

There's no need. The interpreter handles allocation behind the scenes, effectively promoting from one type to another as needed without you doing anything explicit.

Basically, you don't. There's no reason to. If you want to deal with types of known bit size, look at numpy datatypes.

If you want to put data into a specified format, look at the struct module.

The struct module mentioned in the other answers is the thing you need.

An example to make it clear.

import struct

struct.pack('qii', # Format string  here.
            100, # Your 64-bit integer
            50, # Your first 32-bit integer
            25) # Your second 32-bit integer

# This will return the following:
'd\x00\x00\x00\x00\x00\x00\x002\x00\x00\x00\x19\x00\x00\x00'

documentation for the formatting string.

The following snippet from an ipython interpreter session indicates one way of testing the type of an integer. Note, on my system, an int is a 64-bit data type, and a long is a multi-word type.

In [190]: isinstance(1,int)
Out[190]: True    
In [191]: isinstance(1,long)
Out[191]: False    
In [192]: isinstance(1L,long)
Out[192]: True

Also see an answer about sys.getsizeof . This function is not entirely relevant, since some additional overhead bytes are included. For example:

In [194]: import sys    
In [195]: sys.getsizeof(1)
Out[195]: 24
In [196]: sys.getsizeof(1L)
Out[196]: 28

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM