473,608 Members | 2,074 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

fixedint.py enhanced for auto-coercion (fixed-width python integers)

Hi Dan,

I find that when doing bit-twiddling in pure Python,
fixed-width integer support is an extremely handy
capability to have in Python regardless of what
the apologists (for its absence) say.
I added some stuff to fixedint.py to make
x=SByte(80)
x+200 fixedint.Signed Type(8)(24)

the above work. Perhaps you can review the
code to see if there are any major flaws in it?
Right after I started using it, I realized
there has to be a lot more thought put into
the conventions for the coecion rules. What
should
x=SByte(80)
200+x


return for example... ?

----- START OF CODE -----
import operator

def _toFixedUnsigne d(n, b):
"Truncate n to a b-bit unsigned long."
return n & ((1L << b) - 1) # bitmask of b 1's

def _toFixedSigned( n, b):
"Truncate n to a b-bit signed long."
result = _toFixedUnsigne d(n, b)
if result >= (1L << b - 1): # More than "maxint"?
result -= 1L << b # Then wrap around.
return result

class _Integer(object ):
"Abstract base class for SignedType and UnsignedType."
# Numeric conversions
def __long__(self):
return self._value
def __int__(self):
return int(self._value )
def __float__(self) :
return float(self._val ue)
def __nonzero__(sel f):
return self._value != 0
# String conversions.
def __str__(self):
return str(self._value )
# Arithmetic
def __pos__(self):
return self
def __neg__(self):
return type(self)(-self._value)
def __add__(self, other):
if isinstance(othe r, type(self)):
return type(self)(self ._value + other._value)
else:
return type(self)(self ._value + self.__class__( other)._value)
def __sub__(self, other):
if isinstance(othe r, type(self)):
return type(self)(self ._value - other._value)
else:
return type(self)(self ._value - self.__class__( other)._value)
def __mul__(self, other):
if isinstance(othe r, type(self)):
return type(self)(self ._value * other._value)
else:
return type(self)(self ._value * self.__class__( other)._value)
def __floordiv__(se lf, other):
if isinstance(othe r, type(self)):
return type(self)(self ._value // other._value)
else:
return type(self)(self ._value // self.__class__( other)._value)
def __mod__(self, other):
if isinstance(othe r, type(self)):
return type(self)(self ._value % other._value)
else:
return type(self)(self ._value % self.__class__( other)._value)
def __divmod__(self , other):
return self // other, self % other
# Relational
def __cmp__(self, other):
return cmp(long(self), other)
# Bit-bashing
def __lshift__(self , other):
return type(self)(self ._value << other)
def __rshift__(self , other):
return type(self)(self ._value >> other)
def __invert__(self ):
return type(self)(~sel f._value)
def __and__(self, other):
if isinstance(othe r, type(self)):
return type(self)(self ._value & other._value)
else:
return type(self)(self ._value & self.__class__( other)._value)
def __or__(self, other):
if isinstance(othe r, type(self)):
return type(self)(self ._value | other._value)
else:
return type(self)(self ._value | self.__class__( other)._value)
def __xor__(self, other):
if isinstance(othe r, type(self)):
return type(self)(self ._value ^ other._value)
else:
return type(self)(self ._value ^ self.__class__( other)._value)

_utypes = {}

def UnsignedType(bi ts):
"Returns a fixed-width unsigned int type with the given number of bits."
if bits in _utypes:
return _utypes[bits]
else:
class unsigned(_Integ er):
__doc__ = '%d-bit unsigned integer type' % bits
def __init__(self, value):
self._value = _toFixedUnsigne d(value, bits)
def __repr__(self):
return 'fixedint.Unsig nedType(%d)(%d) ' % (bits, self._value)
return unsigned

Byte = UnsignedType(8)
UShort = UnsignedType(16 )
UInt = UnsignedType(32 )
ULong = UnsignedType(64 )

_stypes = {}

def SignedType(bits ):
"Returns a fixed-width signed int type with the given number of bits."
if bits in _stypes:
return _stypes[bits]
else:
class signed(_Integer ):
__doc__ = '%d-bit signed integer type' % bits
def __init__(self, value):
self._value = _toFixedSigned( value, bits)
def __repr__(self):
return 'fixedint.Signe dType(%d)(%d)' % (bits, self._value)
return signed

SByte = SignedType(8)
Short = SignedType(16)
Int = SignedType(32)
Long = SignedType(64)

Feb 3 '06 #1
0 1226

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
1561
by: Raymond Hettinger | last post by:
QOTW: "the DOM API is designed for consultants, not for humans or computers" -- Fredrik Lundh giving solace to a confused DOM API user QOTW: "Python enjoys making tradeoffs that drive *someone* crazy <wink>" -- Michael Hudson's signature line attributed to Tim Peters Discussion ---------- Alex Martelli shows the classic example for the "for-else"
8
1727
by: Christian Seberino | last post by:
c extension compilation gives this gripe about python itself with -Wall and -pedantic switches --> /usr/include/python2.2/longobject.h:48: warning: ISO C89 does not support `long long' Is there any way to avoid this? Chris
30
3428
by: Christian Seberino | last post by:
How does Ruby compare to Python?? How good is DESIGN of Ruby compared to Python? Python's design is godly. I'm wondering if Ruby's is godly too. I've heard it has solid OOP design but then I've also heard there are lots of weird ways to do some things kinda like Perl which is bad for me. Any other ideas?
22
2227
by: Paul Prescod | last post by:
I think that in this case, Python is demonstrably better than Prothon. C:\temp\prothon\Prothon>python ActivePython 2.3.2 Build 232 (ActiveState Corp.) based on Python 2.3.2 (#49, Nov 13 2003, 10:34:54) on win32 Type "help", "copyright", "credits" or "license" for more information. >>> print 2**65 36893488147419103232
8
334
by: Jason Jiang | last post by:
Hi, Could someone recommend a good Python editor? Thanks. Jason
270
8022
by: Jordan | last post by:
Hi everyone, I'm a big Python fan who used to be involved semi regularly in comp.lang.python (lots of lurking, occasional posting) but kind of trailed off a bit. I just wrote a frustration inspired rant on my blog, and I thought it was relevant enough as a wider issue to the Python community to post here for your discussion and consideration. This is not flamebait. I love Python, and I'm not out to antagonise the community. I also...
5
3156
by: Ross | last post by:
Forgive my newbieness - I want to refer to some variables and indirectly alter them. Not sure if this is as easy in Python as it is in C. Say I have three vars: oats, corn, barley I add them to a list: myList Then I want to past that list around and alter one of those values. That is I want to increment the value of corn:
0
8087
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8025
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
1
8179
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8365
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
6847
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6023
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
3993
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
2493
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1620
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.