[docs] [issue16580] Add examples to int.to_bytres and int.from_bytes

Paddy McCarthy report at bugs.python.org
Thu Nov 29 20:25:09 CET 2012


New submission from Paddy McCarthy:

http://docs.python.org/3.3/library/stdtypes.html?highlight=to_bytes#int.to_bytes and http://docs.python.org/3.3/library/stdtypes.html?highlight=to_bytes#int.to_bytes would benefit from an example showing what they do based on simpler coding.

I have such an example that I wrote here: http://paddy3118.blogspot.co.uk/2012/11/some-identities-for-python-inttobytes.html that you can use.

I.e.

>>> n = 2491969579123783355964723219455906992268673266682165637887
>>> length = 25
>>> n2bytesbig    = n.to_bytes(length, 'big')
>>> n2byteslittle = n.to_bytes(length, 'little')
>>> assert n2bytesbig    == bytes( (n >> i*8) & 0xff for i in reversed(range(length)))
>>> assert n2byteslittle == bytes( (n >> i*8) & 0xff for i in range(length))
>>> assert n == sum( n2bytesbig[::-1][i] << i*8 for i in range(length) )
>>> assert n == sum( n2byteslittle[i]    << i*8 for i in range(length) )
>>> assert n == int.from_bytes(n2bytesbig,    byteorder='big')
>>> assert n == int.from_bytes(n2byteslittle, byteorder='little')
>>>

----------
assignee: docs at python
components: Documentation
messages: 176671
nosy: docs at python, paddy3118
priority: normal
severity: normal
status: open
title: Add examples to int.to_bytres and int.from_bytes
type: enhancement
versions: Python 3.3

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


More information about the docs mailing list