Alexandre Vassalotti <alexan...@peadrop.com> added the comment:

I went ahead and coded a new API for converting long integers to byte
arrays and vice-versa. My patch adds two new methods to the long type:
.as_bytes() and .frombytes(). The patch itself is well-documented; but
nevertheless, here's some examples: 

>>> (1024).as_bytes()
b'\x04\x00'
>>> (1024).as_bytes(fixed_length=10)
b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00'
>>> (-1024).as_bytes(fixed_length=10)
b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00'
>>> (-1024).as_bytes(little_endian=True)
b'\x00\xfc'
>>> ((2**16)-1).as_bytes(fixed_length=2, signed=False)
b'\xff\xff'

>>> int.frombytes(b'\x00\x10')
16
>>> int.frombytes(b'\x00\x10', little_endian=True)
4096
>>> int.frombytes(b'\xfc\x00')
-1024
>>> int.frombytes(b'\xfc\x00', signed=False)
64512


This patch depends on another patch posted in issue #6687. So, apply the
other patch before testing this one.

----------
nosy: +alexandre.vassalotti
Added file: http://bugs.python.org/file14695/long_and_bytes_conversion.diff

_______________________________________
Python tracker <rep...@bugs.python.org>
<http://bugs.python.org/issue1023290>
_______________________________________
_______________________________________________
Python-bugs-list mailing list
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com

Reply via email to