Skip to content

Commit 8ec7ab0

Browse files
author
Jacob Beck
committed
Add signed support to newint_bytes
1 parent 5924c81 commit 8ec7ab0

File tree

1 file changed

+9
-8
lines changed

1 file changed

+9
-8
lines changed

src/future/types/newint.py

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -299,18 +299,19 @@ def to_bytes(self, length, byteorder='big', signed=False):
299299
used to represent the integer. If signed is False and a negative integer
300300
is given, an OverflowError is raised.
301301
"""
302-
if signed:
303-
raise NotImplementedError("Not yet implemented. Please contribute a patch at http://python-future.org")
302+
if length < 0:
303+
raise ValueError("length argument must be non-negative")
304+
if length == 0 and self == 0:
305+
return newbytes()
306+
if signed and self < 0:
307+
bits = length * 8
308+
num = (2**bits) + self
304309
else:
305310
if self < 0:
306311
raise OverflowError("can't convert negative int to unsigned")
307312
num = self
308313
if byteorder not in ('little', 'big'):
309314
raise ValueError("byteorder must be either 'little' or 'big'")
310-
if length < 0:
311-
raise ValueError("length argument must be non-negative")
312-
if length == 0 and num == 0:
313-
return newbytes()
314315
h = b'%x' % num
315316
s = newbytes((b'0'*(len(h) % 2) + h).zfill(length*2).decode('hex'))
316317
if len(s) > length:
@@ -335,8 +336,6 @@ def from_bytes(cls, mybytes, byteorder='big', signed=False):
335336
The signed keyword-only argument indicates whether two's complement is
336337
used to represent the integer.
337338
"""
338-
if signed:
339-
raise NotImplementedError("Not yet implemented. Please contribute a patch at http://python-future.org")
340339
if byteorder not in ('little', 'big'):
341340
raise ValueError("byteorder must be either 'little' or 'big'")
342341
if isinstance(mybytes, unicode):
@@ -351,6 +350,8 @@ def from_bytes(cls, mybytes, byteorder='big', signed=False):
351350
# The encode() method has been disabled by newbytes, but Py2's
352351
# str has it:
353352
num = int(native(b).encode('hex'), 16)
353+
if signed and (b[0] & 0x80):
354+
num = num - (2 ** (len(b)*8))
354355
return cls(num)
355356

356357

0 commit comments

Comments
 (0)