[Python-ideas] bitwise operations on bytes

Mark Dickinson dickinsm at gmail.com
Mon Aug 10 11:23:13 CEST 2009


On Sat, Aug 8, 2009 at 10:31 PM, Guido van Rossum<guido at python.org> wrote:
> -- the struct module only handles sizes 2, 4 and 8. I can hack it by
> going via a hex representation:
>
>  i = 10**100
>  b = bytes.fromhex(hex(i)[2:])
>  import binascii
>  j = int(binascii.hexlify(b), 16)
>  assert j == i
>
> but this is a pretty gross hack.

The first part also doesn't work if hex(i) has odd length.
[py3k]:

>>> bytes.fromhex(hex(10**99)[2:])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: non-hexadecimal number found in fromhex() arg at position 82

I think the fact that it's non-trivial to get this right first
time is further evidence that it would be useful to have
built-in int <-> bytes conversions somewhere.

Mark



More information about the Python-ideas mailing list