Convert python long/int to fixed size byte array

cdecker picture cdecker · Jan 4, 2012 · Viewed 103.7k times · Source

I'm trying to implement RC4 and DH key exchange in python. Problem is that I have no idea about how to convert the python long/int from the key exchange to the byte array I need for the RC4 implementation. Is there a simple way to convert a long to the required length byte array?

Update: forgot to mention that the numbers I'm dealing with are 768 bit unsigned integers.

Answer

Jack O'Connor picture Jack O'Connor · Jan 21, 2015

With Python 3.2 and later, you can use int.to_bytes and int.from_bytes: https://docs.python.org/3/library/stdtypes.html#int.to_bytes