简体   繁体   中英

When I use ctypes.c_int() it returns a different number?

When I use the code below, it returns a different number.

numb = 5000000000
n = ctypes.c_int(numb)

the number it converts: 705032703

5,000,000,000 is too large for a 32-bit integer. You can see below it just truncates to 32 bits:

>>> n=5000000000
>>> hex(n)
'0x12a05f200'         # 33 bits
>>> import ctypes
>>> hex(ctypes.c_int(n).value)
'0x2a05f200'          # dropped the 33rd bit

You can see the same thing by ANDing with a 32-bit mask:

>>> n & 0xffffffff
705032704

ctypes exposes the C-compatible types, with ctypes.c_int() being an exposure of the signed int type, which could be 32-bit or 64-bit depending on the platform (or possibly even narrower or wider).

In your instance, your c_int is a 32-bit type, and a 32-bit signed int can hold the range [-2147483648, 2147483647] , or 4294967296 possible values.

So it can't hold your 5000000000 (5 billion) as-is, and it's implementation-defined how overflow is handled.

If you want to hold large numbers, it's recommended to used fixed-width types like c_int64 so you know exactly what you're dealing with, as c_int and c_long have some size guarantees but are otherwise implementation/platform specific.

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