Web Hosting Philippines, Offshore Programming, Offshore SEO Philippines, Cheap Webhosting Manila Philippines
Home -> Resources -> Python -> Casting Python integers into signed 32-bit equivalents

Casting Python integers into signed 32-bit equivalents

When implementing bit-twiddling routines in C/C++, one frequently takes for granted the implicit convertibility between signed and unsigned values of the same bit pattern and bitwidth. For example, 0xFFFFFFFF, when cast to a signed 32-bit integer will return -1. In Python however, all integers are signed and when a positive integer exceeds the maximum possible 32-bit signed value, 2147483647, it is automatically promoted to a long, e.g. 2147483648L.

The following routine will take any integer value up to 0xFFFFFFFF, treat it like it had the unsigned 32-bit integer bit pattern and return the equivalent signed twos-complement integer value much like the corresponding cast in C would.

The return value is guaranteed to be <type 'int'> and not <type 'long'>. One application for this is in IronPython when calling .NET Framework APIs which want an Int32 for which you want to express the value as an unsigned 32-bit integer literal (e.g. color + alpha values - 0xRRGGBBAA). It might also be useful when porting C-originated bit-twiddling algorithms over to Python.

def int32(x):
  if x>0xFFFFFFFF:
    raise OverflowError
  if x>0x7FFFFFFF:
    x=int(0x100000000-x)
    if x<2147483648:
      return -x
    else:
      return -2147483648
  return x
 Want to tip via bitcoin?

(address string below for double checking)
 1KDgw4y5AUSUhmRVQSWiVS43YvrrxLmc8u

© 2017 by Andy Sy
last updated: 2007-Sep-9

NeoTitans- Offshore Outsourced Corporate Web and Software Development Internet Marketing SEO

Web Development / Rich Internet Applications (RIA) Development

Programming Languages

Platforms

Database Development




Offshore Outsourced Corporate Web and Software Development Internet Marketing SEO
VPS Hosting, Ruby on Rails hosting Philippines, RoR hosting
   © 2003-2015 Neotitans Technologies Inc.