Python doesn't have builtin unsigned types. you can use abs() function.
A long is an integer type value that has unlimited length. By converting a string into long we are translating the value of string type to long type. In Python3 int is upgraded to long by default which means that all the integers are long in Python3. So we can use int() to convert a string to long in Python.
int (signed integers) − They are often called just integers or ints, are positive or negative whole numbers with no decimal point. long (long integers ) − Also called longs, they are integers of unlimited size, written like integers and followed by an uppercase or lowercase L.
Type int(x) to convert x to a plain integer. Type long(x) to convert x to a long integer. Type float(x) to convert x to a floating-point number.
import ctypes
number = lv & 0xFFFFFFFF
signed_number = ctypes.c_long(number).value
You're working in a high-level scripting language; by nature, the native data types of the system you're running on aren't visible. You can't cast to a native signed int with code like this.
If you know that you want the value converted to a 32-bit signed integer--regardless of the platform--you can just do the conversion with the simple math:
iv = 0xDEADBEEF
if(iv & 0x80000000):
iv = -0x100000000 + iv
Essentially, the problem is to sign extend from 32 bits to... an infinite number of bits, because Python has arbitrarily large integers. Normally, sign extension is done automatically by CPU instructions when casting, so it's interesting that this is harder in Python than it would be in, say, C.
By playing around, I found something similar to BreizhGatch's function, but that doesn't require a conditional statement. n & 0x80000000
extracts the 32-bit sign bit; then, the -
keeps the same 32-bit representation but sign-extends it; finally, the extended sign bits are set on n
.
def toSigned32(n):
n = n & 0xffffffff
return n | (-(n & 0x80000000))
Bit Twiddling Hacks suggests another solution that perhaps works more generally. n ^ 0x80000000
flips the 32-bit sign bit; then - 0x80000000
will sign-extend the opposite bit. Another way to think about it is that initially, negative numbers are above positive numbers (separated by 0x80000000
); the ^
swaps their positions; then the -
shifts negative numbers to below 0.
def toSigned32(n):
n = n & 0xffffffff
return (n ^ 0x80000000) - 0x80000000
You may use struct library to convert values like that. It's ugly, but works:
from struct import pack, unpack
signed = unpack('l', pack('L', lv & 0xffffffff))[0]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With