QNA > H > How To Convert Int To Byte In Python

How to convert int to byte in Python

Do you want one byte or more than one - in theory a Python integer could be capable of being stored in one byte, or 4, or 20, or 400 …

You can use the array [1]module.

If you know that your integer fits into 4 bytes, you could do :

  1. import array 
  2. the_int = 56287 
  3. ar = array.array('l',[the_int]) 
  4. bytes = ar.tobytes() 
  5. for i in bytes: 
  6. print(i) 

On a linux machine this yields :

  1. 223 
  2. 219 

And 56287 is 219 * 256 + 223

Showing that in this case Unix stores the values in little endian format.

Another way to do it (for positive values) - is extract each byte manually but looking at the remainders when the value is divided repeatedly by 256

  1. the_int = 56287 
  2. while the_int > 0: 
  3. the_int, rem = divmod(the_int, 256) print(rem) 

This yields :

  1. 223 
  2. 219 

I.e. little endian first.

Finally - thank you Jeremy Stafford you can do it really simply using the int.to_bytes() [2] method :

  1. the_int = 56287 
  2. for byte in the_int.to_bytes(4,'little'): 
  3. print(byte) 

Provides :

  1. 223 
  2. 219 

That is 4 bytes in little-endian format.

Footnotes

[1] array - Efficient arrays of numeric values - Python 3.8.2 documentation[2] Built-in Types - Python 3.8.2 documentation

Di Horbal Mcnaughton

Qual è lo scopo di "end" in Python? :: Perché NumPy è veloce?
Link utili