[New-bugs-announce] [issue13535] Improved two's complement arithmetic support: to_signed() and to_unsigned()

Nick Coghlan report at bugs.python.org
Tue Dec 6 01:49:34 CET 2011


New submission from Nick Coghlan <ncoghlan at gmail.com>:

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)

----------
components: Interpreter Core, Library (Lib)
messages: 148896
nosy: ncoghlan
priority: normal
severity: normal
stage: needs patch
status: open
title: Improved two's complement arithmetic support: to_signed() and to_unsigned()
type: feature request
versions: Python 3.3

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue13535>
_______________________________________


More information about the New-bugs-announce mailing list