When I use the code below, it returns a different number.
numb = 5000000000 n = ctypes.c_int(numb)
the number it converts : 705032703
UPDATE
now it doesn't give error. and performed the operation. However, the number it returns is still different. It should return the number I entered. but it does not return.
main.py
numb = 5000000000
n = ctypes.c_int64(numb)
x = hello_world(n)
print(x)
golang code that I converted to c code
main.go
package main
import "C"
func helloWorld(x int64) int64 {
s := int64(1)
for i := int64(1); i < x; i {
s = i
}
return s
}
CodePudding user response:
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
CodePudding user response:
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.