homepage

This issue tracker has been migrated to GitHub , and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

Author ncoghlan
Recipients ncoghlan
Date 2011年12月06日.00:49:33
SpamBayes Score 0.00011114069
Marked as misclassified No
Message-id <1323132574.65.0.0748252638501.issue13535@psf.upfronthosting.co.za>
In-reply-to
Content
This RFE proposes two new methods "to_signed" and "to_unsigned" on 'int' objects and on the numbers.Integral ABC.
Semantics (and number.Integral implementation):
def to_unsigned(self, bits):
 "Convert this integer to its unsigned two's complement equivalent for the given bit length"
 if self.bit_length() >= bits:
 raise ValueError("{} is too large for {}-bit two's complement
precision".format(self, bits))
 if self >= 0:
 return self
 return 2**bits + self # self is known to be negative at this point
def to_signed(self, bits):
 "Convert an integer in two's complement format to its signed equivalent for the given bit length"
 if self < 0:
 raise ValueError("{} is already signed".format(self))
 if self.bit_length() > bits:
 raise ValueError("{} is too large for {}-bit two's complement
precision".format(self, bits))
 upper_bound = 2**bits
 if self < (upper_bound / 2):
 return self
 return upper_bound - self
To add these methods to numbers.Integral, a concrete numbers.Integral.bit_length() operation will also be needed. This can be implemented simply as:
def bit_length(self):
 return int(self).bit_length()
(Initial concept from this python-ideas thread: http://mail.python.org/pipermail/python-ideas/2011-December/012989.html)
History
Date User Action Args
2011年12月06日 00:49:34ncoghlansetrecipients: + ncoghlan
2011年12月06日 00:49:34ncoghlansetmessageid: <1323132574.65.0.0748252638501.issue13535@psf.upfronthosting.co.za>
2011年12月06日 00:49:34ncoghlanlinkissue13535 messages
2011年12月06日 00:49:33ncoghlancreate

AltStyle によって変換されたページ (->オリジナル) /