简体   繁体   English

如何确定Python中的数字是32位还是64位整数?

[英]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. 我想区分Python中的32位和64位整数。 In C it's very easy as we can declare variables using int_64 and int_32 . 在C中,我们可以使用int_64int_32声明变量,这非常简单。 But in Python how do we differentiate between 32-bit integers and 64-bit integers? 但是在Python中我们如何区分32位整数和64位整数?

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. 如果要处理已知位大小的类型,请查看numpy数据类型。

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. 其他答案中提到的struct模块就是你需要的东西。

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. 来自ipython解释器会话的以下片段指示了一种测试整数类型的方法。 Note, on my system, an int is a 64-bit data type, and a long is a multi-word type. 注意,在我的系统上, int是64位数据类型, long是多字类型。

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 . 另请参阅有关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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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