[Python-ideas] Negative hexes
Nick Coghlan
ncoghlan at gmail.com
Tue Dec 6 01:14:03 CET 2011
On Tue, Dec 6, 2011 at 9:10 AM, Antoine Pitrou <solipsis at pitrou.net> wrote:
> On Tue, 6 Dec 2011 08:19:53 +1000
> Nick Coghlan <ncoghlan at gmail.com> wrote:
>> On Tue, Dec 6, 2011 at 3:15 AM, Antoine Pitrou <solipsis-xNDA5Wrcr86sTnJN9+BGXg at public.gmane.org> wrote:
>> >> That is, currently:
>> >>
>> >> >>> "{:.4x}".format(31)
>> >> Traceback (most recent call last):
>> >> File "<stdin>", line 1, in <module>
>> >> ValueError: Precision not allowed in integer format specifier
>> >
>> > This is so poorly discoverable that I don't think it's worth it.
>> > Guido's approach looks sufficient to me.
>>
>> I agree the formatting approach is way too obscure, but did you see my
>> later suggestion of an "as_twos_complement(bit_length)" conversion
>> method on int objects? (we could actually provide a more generic
>> version on numbers.Integer as well)
>
> Ah, right. Yes, I think that would be useful, although a shorter name
> would be nicer. to_unsigned() perhaps?
Hmm, in the sense that the answer we're getting is the same answer you
would get with a cast to an unsigned type at the C level? I think
that's a little misleading - conceptually, the number is still signed,
we're just representing it differently (i.e. explicitly using the twos
complement form, rather than the the normal sign bit).
I'd be OK with dropping the explicit 'twos' qualifier, though - then
the method name could just be "to_complement()".
I guess we'd also want a "to_signed()" to reverse the process:
def to_complement(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
Regards,
Nick.
--
Nick Coghlan | ncoghlan at gmail.com | Brisbane, Australia
More information about the Python-ideas
mailing list